<template>
  <div class="dashboard">
    <!-- 顶部导航栏 -->
    <header class="dashboard-header">
      <div class="header-content">
        <div class="logo">
          <h1>🔐 {{ $t('dashboard.title') }}</h1>
        </div>
        <div class="user-info">
          <button @click="toggleLanguage" class="lang-toggle-btn" :title="$t('language.switchTo')">
            {{ currentLocale === 'zh-CN' ? '🇨🇳' : '🇺🇸' }}
          </button>
          <button @click="toggleTheme" class="theme-toggle-btn" :title="isDark() ? $t('theme.switchToLight') : $t('theme.switchToDark')">
            {{ isDark() ? '🌞' : '🌙' }}
          </button>
          <span class="username">{{ userInfo.nickname || userInfo.username }}</span>
          <button @click="logout" class="logout-btn">{{ $t('common.logout') }}</button>
        </div>
      </div>
    </header>

    <!-- 主要内容区 -->
    <main class="dashboard-main">
      <!-- 侧边栏 -->
      <aside class="sidebar">
        <nav class="nav-menu">
          <div class="menu-item" :class="{ active: activeTab === 'overview' }" @click="setActiveTab('overview')">
            📊 {{ $t('nav.overview') }}
          </div>
          <div class="menu-item" :class="{ active: activeTab === 'accounts' }" @click="setActiveTab('accounts')">
            📋 {{ $t('nav.accounts') }}
          </div>
          <div class="menu-item" :class="{ active: activeTab === 'notifications' }" @click="setActiveTab('notifications')">
            <span>🔔 {{ $t('nav.notifications') }}</span>
            <span v-if="notificationStats.total > 0" class="menu-badge">{{ notificationStats.total }}</span>
          </div>
          <div class="menu-item" :class="{ active: activeTab === 'categories' }" @click="setActiveTab('categories')">
            📁 {{ $t('nav.categories') }}
          </div>
          <div class="menu-item" :class="{ active: activeTab === 'security' }" @click="setActiveTab('security')">
            🔒 {{ $t('nav.security') }}
          </div>
          <div class="menu-item" :class="{ active: activeTab === 'profile' }" @click="setActiveTab('profile')">
            👤 {{ $t('nav.profile') }}
          </div>
        </nav>
      </aside>

      <!-- 内容区域 -->
      <section class="content">
        <!-- 数据概览 -->
        <div v-if="activeTab === 'overview'" class="tab-content">
          <h2>{{ $t('overview.title') }}</h2>
          <div class="stats-grid">
            <div class="stat-card">
              <div class="stat-icon">📋</div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.totalAccounts }}</div>
                <div class="stat-label">{{ $t('overview.totalAccounts') }}</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon">📁</div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.totalCategories }}</div>
                <div class="stat-label">{{ $t('overview.totalCategories') }}</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon">⭐</div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.favoriteAccounts }}</div>
                <div class="stat-label">{{ $t('overview.favoriteAccounts') }}</div>
              </div>
            </div>
            <div class="stat-card">
              <div class="stat-icon">⚠️</div>
              <div class="stat-info">
                <div class="stat-number">{{ stats.expiringAccounts }}</div>
                <div class="stat-label">{{ $t('overview.expiringAccounts') }}</div>
              </div>
            </div>
          </div>

          <!-- 通知提醒 -->
          <div class="notifications-section" v-if="notifications.length > 0">
            <div class="section-header">
              <h3>🔔 {{ $t('overview.notificationReminders') }}</h3>
              <span class="badge" v-if="notificationStats.total > 0">{{ notificationStats.total }}</span>
            </div>
            <div class="notifications-list">
              <div v-for="notification in notifications.slice(0, 5)" :key="notification.id" class="notification-item" :class="notification.priority">
                <div class="notification-icon">{{ getNotificationIcon(notification.type) }}</div>
                <div class="notification-content">
                  <div class="notification-title">{{ notification.title }}</div>
                  <div class="notification-message">{{ notification.message }}</div>
                  <div class="notification-time">{{ formatTime(notification.created_at) }}</div>
                </div>
                <div class="notification-priority">
                  <span class="priority-badge" :class="`priority-${notification.priority}`">
                    {{ getPriorityText(notification.priority) }}
                  </span>
                </div>
              </div>
            </div>
            <button v-if="notifications.length > 5" @click="setActiveTab('notifications')" class="view-all-btn">
              {{ $t('overview.viewAllNotifications', { count: notifications.length }) }}
            </button>
          </div>

          <!-- 统计图表 -->
          <div class="charts-section">
            <h3>📊 {{ $t('overview.dataAnalysis') }}</h3>

            <!-- 分类分布 -->
            <div class="chart-container">
              <div class="chart-header">
                <h4>{{ $t('overview.categoryDistribution') }}</h4>
                <span class="chart-subtitle">{{ $t('overview.categorySubtitle') }}</span>
              </div>
              <div class="pie-chart">
                <div class="pie-chart-legend">
                  <div v-for="(item, index) in categoryStats" :key="item.category_id" class="legend-item">
                    <div class="legend-color" :style="{ background: getChartColor(index) }"></div>
                    <div class="legend-info">
                      <span class="legend-name">{{ item.category_name || $t('overview.uncategorized') }}</span>
                      <span class="legend-value">{{ item.count }}个 ({{ getPercentage(item.count, stats.totalAccounts) }}%)</span>
                    </div>
                  </div>
                </div>
                <div class="pie-chart-visual">
                  <svg viewBox="0 0 200 200" class="pie-svg">
                    <circle cx="100" cy="100" r="80" fill="none" stroke="#f0f0f0" stroke-width="40"/>
                    <circle
                      v-for="(segment, index) in pieChartSegments"
                      :key="index"
                      cx="100"
                      cy="100"
                      r="80"
                      fill="none"
                      :stroke="segment.color"
                      stroke-width="40"
                      :stroke-dasharray="`${segment.dashArray} ${502.4 - segment.dashArray}`"
                      :stroke-dashoffset="segment.dashOffset"
                      transform="rotate(-90 100 100)"
                    />
                  </svg>
                  <div class="pie-center">
                    <div class="pie-total">{{ stats.totalAccounts }}</div>
                    <div class="pie-label">{{ $t('overview.totalAccountsLabel') }}</div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 使用趋势 -->
            <div class="chart-container">
              <div class="chart-header">
                <h4>{{ $t('overview.usageTrend') }}</h4>
                <span class="chart-subtitle">{{ $t('overview.usageSubtitle') }}</span>
              </div>
              <div class="line-chart">
                <div class="chart-grid">
                  <div v-for="i in 5" :key="i" class="grid-line"></div>
                </div>
                <div class="chart-bars">
                  <div v-for="(day, index) in usageTrend" :key="index" class="bar-item">
                    <div class="bar-wrapper">
                      <div
                        class="bar"
                        :style="{ height: getBarHeight(day.count) + '%', background: getGradientColor(day.count) }"
                        :title="`${day.count}次`"
                      >
                        <span class="bar-value">{{ day.count }}</span>
                      </div>
                    </div>
                    <div class="bar-label">{{ formatDayLabel(day.date) }}</div>
                  </div>
                </div>
              </div>
            </div>

            <!-- 安全健康度 -->
            <div class="chart-container">
              <div class="chart-header">
                <h4>{{ $t('overview.securityHealth') }}</h4>
                <span class="chart-subtitle">{{ $t('overview.securityHealthSubtitle') }}</span>
              </div>
              <div class="health-score-chart">
                <div class="score-gauge">
                  <svg viewBox="0 0 200 120" class="gauge-svg">
                    <!-- 背景弧 -->
                    <path
                      d="M 20 100 A 80 80 0 0 1 180 100"
                      fill="none"
                      stroke="#f0f0f0"
                      stroke-width="20"
                      stroke-linecap="round"
                    />
                    <!-- 进度弧 -->
                    <path
                      d="M 20 100 A 80 80 0 0 1 180 100"
                      fill="none"
                      :stroke="getHealthColor(healthScore)"
                      stroke-width="20"
                      stroke-linecap="round"
                      :stroke-dasharray="`${healthScore * 2.51} 251`"
                    />
                  </svg>
                  <div class="gauge-center">
                    <div class="gauge-score">{{ healthScore }}</div>
                    <div class="gauge-label">{{ getHealthLabel(healthScore) }}</div>
                  </div>
                </div>
                <div class="health-details">
                  <div class="health-item">
                    <span class="health-icon">🔐</span>
                    <span class="health-text">{{ $t('overview.strongPasswords') }}</span>
                    <span class="health-count">{{ healthDetails.strong_passwords || 0 }}</span>
                  </div>
                  <div class="health-item">
                    <span class="health-icon">⚠️</span>
                    <span class="health-text">{{ $t('overview.weakPasswords') }}</span>
                    <span class="health-count warning">{{ healthDetails.weak_passwords || 0 }}</span>
                  </div>
                  <div class="health-item">
                    <span class="health-icon">⏰</span>
                    <span class="health-text">{{ $t('overview.expiringAccounts') }}</span>
                    <span class="health-count warning">{{ stats.expiringAccounts || 0 }}</span>
                  </div>
                  <div class="health-item">
                    <span class="health-icon">⭐</span>
                    <span class="health-text">{{ $t('overview.activeAccounts') }}</span>
                    <span class="health-count">{{ healthDetails.active_accounts || 0 }}</span>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <div class="recent-section">
            <h3>{{ $t('overview.recentlyAdded') }}</h3>
            <div class="recent-accounts">
              <div v-for="account in recentAccounts" :key="account.id" class="account-item">
                <div class="account-icon">🌐</div>
                <div class="account-info">
                  <div class="account-name">{{ account.title || account.name }}</div>
                  <div class="account-category">{{ account.category?.name || $t('overview.uncategorized') }} (ID: {{ account.category_id || 'null' }})</div>
                </div>
                <div class="account-date">{{ formatDate(account.created_at) }}</div>
              </div>
            </div>
          </div>

          <!-- 快捷键帮助 -->
          <div class="shortcuts-help">
            <h3>⌨️ {{ $t('overview.keyboardShortcuts') }}</h3>
            <div class="shortcuts-grid">
              <div class="shortcut-item">
                <span class="shortcut-key">Ctrl + N</span>
                <span class="shortcut-desc">{{ $t('overview.createAccount') }}</span>
              </div>
              <div class="shortcut-item">
                <span class="shortcut-key">Ctrl + F</span>
                <span class="shortcut-desc">{{ $t('overview.searchAccount') }}</span>
              </div>
              <div class="shortcut-item">
                <span class="shortcut-key">Ctrl + E</span>
                <span class="shortcut-desc">{{ $t('shortcuts.exportData') }}</span>
              </div>
              <div class="shortcut-item">
                <span class="shortcut-key">Ctrl + 1-6</span>
                <span class="shortcut-desc">{{ $t('shortcuts.switchTab') }}</span>
              </div>
              <div class="shortcut-item">
                <span class="shortcut-key">Esc</span>
                <span class="shortcut-desc">{{ $t('overview.closeModal') }}</span>
              </div>
            </div>
          </div>
        </div>

        <!-- 账号管理 -->
        <div v-if="activeTab === 'accounts'" class="tab-content">
          <div class="content-header">
            <h2>{{ $t('account.management') }}</h2>
            <div class="actions">
              <button @click="toggleBatchMode" class="btn-secondary">
                {{ batchMode ? '✓ ' + $t('account.exitBatchMode') : '☑ ' + $t('account.batchMode') }}
              </button>
              <button @click="addAccount" class="btn-primary">+ {{ $t('account.addAccount') }}</button>
              <button @click="refreshAccounts" class="btn-secondary">🔄 {{ $t('account.refresh') }}</button>
            </div>
          </div>

          <!-- 批量操作工具栏 -->
          <div v-if="batchMode" class="batch-toolbar">
            <div class="batch-info">
              <label class="checkbox-label">
                <input
                  type="checkbox"
                  :checked="isAllSelected"
                  :indeterminate="isIndeterminate"
                  @change="toggleSelectAll"
                  class="batch-checkbox"
                >
                <span>{{ selectedAccounts.length > 0 ? `已选择 ${selectedAccounts.length} 项` : '全选' }}</span>
              </label>
            </div>
            <div v-if="selectedAccounts.length > 0" class="batch-actions">
              <button @click="batchExportAccounts" class="btn-secondary">📤 导出选中</button>
              <select @change="(e: any) => batchMoveCategory(parseInt(e.target.value))" class="batch-select">
                <option value="">移动到分类...</option>
                <option v-for="category in categories" :key="category.id" :value="category.id">
                  {{ category.name }}
                </option>
              </select>
              <button @click="batchDeleteAccounts" class="btn-danger">🗑️ 删除选中</button>
            </div>
          </div>

          <div class="search-bar">
            <input v-if="!showAdvancedSearch" v-model="searchQuery" placeholder="搜索账号名称或网站..." class="search-input">
            <select v-if="!showAdvancedSearch" v-model="filterCategory" class="category-filter">
              <option value="">所有分类</option>
              <option v-for="category in categories" :key="category.id" :value="category.name">
                {{ category.name }}
              </option>
            </select>
            <button @click="toggleAdvancedSearch" class="btn-secondary">
              {{ showAdvancedSearch ? '✕ 关闭高级搜索' : '🔍 高级搜索' }}
            </button>
          </div>

          <!-- 高级搜索面板 -->
          <div v-if="showAdvancedSearch" class="advanced-search-panel">
            <h4>🔍 高级搜索</h4>

            <div class="search-filters">
              <div class="filter-row">
                <div class="filter-group">
                  <label>关键词</label>
                  <input v-model="advancedSearchFilters.keyword" placeholder="搜索标题、网站、备注..." class="form-input">
                </div>
                <div class="filter-group">
                  <label>分类</label>
                  <select v-model="advancedSearchFilters.category" class="form-input">
                    <option value="">全部</option>
                    <option v-for="category in categories" :key="category.id" :value="category.name">
                      {{ category.name }}
                    </option>
                  </select>
                </div>
              </div>

              <div class="filter-row">
                <div class="filter-group">
                  <label>网站</label>
                  <input v-model="advancedSearchFilters.website" placeholder="搜索网站..." class="form-input">
                </div>
                <div class="filter-group">
                  <label>用户名</label>
                  <input v-model="advancedSearchFilters.username" placeholder="搜索用户名..." class="form-input">
                </div>
              </div>

              <div class="filter-row">
                <div class="filter-group">
                  <label>创建时间从</label>
                  <input v-model="advancedSearchFilters.dateFrom" type="date" class="form-input">
                </div>
                <div class="filter-group">
                  <label>到</label>
                  <input v-model="advancedSearchFilters.dateTo" type="date" class="form-input">
                </div>
              </div>

              <div class="filter-row">
                <div class="filter-group">
                  <label>过期时间</label>
                  <select v-model="advancedSearchFilters.hasExpiry" class="form-input">
                    <option :value="null">全部</option>
                    <option :value="true">有过期时间</option>
                    <option :value="false">无过期时间</option>
                  </select>
                </div>
                <div class="filter-group">
                  <label>收藏状态</label>
                  <select v-model="advancedSearchFilters.isFavorite" class="form-input">
                    <option :value="null">全部</option>
                    <option :value="true">已收藏</option>
                    <option :value="false">未收藏</option>
                  </select>
                </div>
              </div>
            </div>

            <!-- 搜索历史 -->
            <div v-if="searchHistory.length > 0" class="search-history">
              <label>搜索历史：</label>
              <div class="history-tags">
                <span
                  v-for="(keyword, index) in searchHistory"
                  :key="index"
                  class="history-tag"
                  @click="useSearchHistory(keyword)"
                >
                  {{ keyword }}
                </span>
              </div>
            </div>

            <div class="search-actions">
              <button @click="applyAdvancedSearch" class="btn-primary">🔍 搜索 ({{ filteredAccounts.length }} 条结果)</button>
              <button @click="resetAdvancedFilters" class="btn-secondary">重置</button>
            </div>
          </div>

          <!-- 骨架屏加载状态 -->
          <div v-if="isLoadingAccounts" class="accounts-grid">
            <div v-for="i in 6" :key="'skeleton-' + i" class="account-card skeleton-card">
              <div class="card-header">
                <div class="skeleton skeleton-title"></div>
                <div class="skeleton skeleton-actions"></div>
              </div>
              <div class="card-content">
                <div class="skeleton skeleton-line"></div>
                <div class="skeleton skeleton-line short"></div>
                <div class="skeleton skeleton-line shorter"></div>
              </div>
            </div>
          </div>

          <!-- 实际账号列表 -->
          <div v-else class="accounts-grid">
            <div v-for="account in filteredAccounts" :key="account.id" class="account-card" :class="{ 'batch-selected': selectedAccounts.includes(account.id) }">
              <div class="card-header">
                <div class="account-title-wrapper">
                  <input
                    v-if="batchMode"
                    type="checkbox"
                    :checked="selectedAccounts.includes(account.id)"
                    @change="toggleSelectAccount(account.id)"
                    class="account-checkbox"
                    @click.stop
                  >
                  <div class="account-title">{{ account.title || account.name }}</div>
                </div>
                <div class="account-actions">
                  <button @click="viewAccountDetails(account)" class="action-btn" title="查看详情">👁️</button>
                  <button @click="copyPassword(account)" class="action-btn" title="复制密码">📋</button>
                  <button @click="editAccount(account)" class="action-btn" title="编辑">✏️</button>
                  <button @click="deleteAccount(account)" class="action-btn delete" title="删除">🗑️</button>
                </div>
              </div>
              <div class="card-content">
                <div class="account-detail">
                  <span class="label">{{ $t('account.website') }}:</span>
                  <span class="value">{{ account.website || '未设置' }}</span>
                </div>
                <div class="account-detail">
                  <span class="label">{{ $t('account.username') }}:</span>
                  <span class="value encrypted-field" title="点击查看详情按钮解密显示">{{ account.username_encrypted ? '●●●●●●●●' : '未设置' }}</span>
                </div>
                <div class="account-detail">
                  <span class="label">{{ $t('account.category') }}:</span>
                  <span class="category-tag">{{ account.category?.name || $t('overview.uncategorized') }}</span>
                  <small style="color: #999; margin-left: 8px;">(ID: {{ account.category_id || 'null' }})</small>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 通知中心 -->
        <div v-if="activeTab === 'notifications'" class="tab-content">
          <div class="content-header">
            <h2>{{ $t('nav.notifications') }}</h2>
            <button @click="loadNotifications" class="btn-secondary">🔄 {{ $t('account.refresh') }}</button>
          </div>

          <!-- 通知统计 -->
          <div class="notification-stats">
            <div class="stat-item" @click="filterNotifications('all')" :class="{ active: notificationFilter === 'all' }">
              <div class="stat-number">{{ notificationStats.total || 0 }}</div>
              <div class="stat-label">全部通知</div>
            </div>
            <div class="stat-item" @click="filterNotifications('high')" :class="{ active: notificationFilter === 'high' }">
              <div class="stat-number">{{ notificationStats.high_priority || 0 }}</div>
              <div class="stat-label">{{ $t('notification.high') }}{{ $t('notification.priority') }}</div>
            </div>
            <div class="stat-item" @click="filterNotifications('expiring')" :class="{ active: notificationFilter === 'expiring' }">
              <div class="stat-number">{{ notificationStats.expiring || 0 }}</div>
              <div class="stat-label">{{ $t('overview.expiringAccounts') }}</div>
            </div>
            <div class="stat-item" @click="filterNotifications('expired')" :class="{ active: notificationFilter === 'expired' }">
              <div class="stat-number">{{ notificationStats.expired || 0 }}</div>
              <div class="stat-label">已过期</div>
            </div>
          </div>

          <!-- 通知列表 -->
          <div class="notifications-container">
            <div v-if="filteredNotifications.length === 0" class="empty-state">
              <div class="empty-icon">✅</div>
              <div class="empty-text">{{ $t('notification.noNotifications') }}</div>
            </div>
            <div v-else class="notifications-full-list">
              <div v-for="notification in filteredNotifications" :key="notification.id" class="notification-card" :class="`priority-${notification.priority}`">
                <div class="notification-header">
                  <div class="notification-icon-large">{{ getNotificationIcon(notification.type) }}</div>
                  <div class="notification-info">
                    <div class="notification-title-large">{{ notification.title }}</div>
                    <div class="notification-time-large">{{ formatTime(notification.created_at) }}</div>
                  </div>
                  <span class="priority-badge-large" :class="`priority-${notification.priority}`">
                    {{ getPriorityText(notification.priority) }}
                  </span>
                </div>
                <div class="notification-body">
                  <p>{{ notification.message }}</p>
                  <div v-if="notification.account_title" class="notification-account">
                    <span>相关账号: </span>
                    <strong>{{ notification.account_title }}</strong>
                  </div>
                </div>
                <div v-if="notification.type === 'password_expired' || notification.type === 'password_expiring'" class="notification-actions">
                  <button @click="goToAccount(notification.account_id)" class="action-link">立即处理</button>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 分类管理 -->
        <div v-if="activeTab === 'categories'" class="tab-content">
          <div class="content-header">
            <h2>{{ $t('nav.categories') }}</h2>
            <button @click="addCategory" class="btn-primary">+ {{ $t('category.addCategory') }}</button>
          </div>

          <div class="categories-list">
            <div v-for="category in categories" :key="category.id" class="category-item">
              <div class="category-info">
                <div class="category-name">{{ category.name }}</div>
                <div class="category-desc">{{ category.description || '无描述' }}</div>
              </div>
              <div class="category-stats">
                <span class="account-count">{{ category.account_count || 0 }} 个账号</span>
              </div>
              <div class="category-actions">
                <button @click="editCategory(category)" class="action-btn">✏️</button>
                <button @click="deleteCategory(category)" class="action-btn delete">🗑️</button>
              </div>
            </div>
          </div>
        </div>

        <!-- 安全设置 -->
        <div v-if="activeTab === 'security'" class="tab-content">
          <h2>{{ $t('nav.security') }}</h2>

          <!-- 密码安全 -->
          <div class="security-section">
            <h3>🔐 密码安全</h3>
            <div class="security-cards">
              <div class="security-card">
                <div class="card-header">
                  <h4>主密码</h4>
                  <span class="status-badge good">安全</span>
                </div>
                <p>主密码用于加密所有存储的账号数据，建议定期更换</p>
                <div class="card-info">
                  <span>上次修改：{{ securityInfo.masterPasswordLastChanged || '从未' }}</span>
                </div>
                <button @click="showChangePasswordModal = true" class="btn-primary">修改主密码</button>
              </div>

              <div class="security-card">
                <div class="card-header">
                  <h4>登录密码</h4>
                  <span class="status-badge good">安全</span>
                </div>
                <p>用于登录账号管理系统的密码</p>
                <div class="card-info">
                  <span>上次修改：{{ securityInfo.loginPasswordLastChanged || '从未' }}</span>
                </div>
                <button @click="showChangeLoginPasswordModal = true" class="btn-secondary">修改登录密码</button>
              </div>
            </div>
          </div>

          <!-- 加密设置 -->
          <div class="security-section">
            <h3>🔒 加密设置</h3>
            <div class="security-card">
              <div class="card-header">
                <h4>数据加密方式</h4>
                <span class="status-badge">{{ securityInfo.encryptMethod || 'AES-256-GCM' }}</span>
              </div>
              <p>选择用于加密存储数据的算法，更改后需要重新加密所有数据</p>
              <div class="encrypt-options">
                <div class="form-group">
                  <label>选择加密算法：</label>
                  <select v-model="selectedEncryptMethod" class="form-select">
                    <option v-for="method in encryptMethods" :key="method.value" :value="method.value">
                      {{ method.label }} - {{ method.description }}
                    </option>
                  </select>
                </div>
                <button @click="changeEncryptMethod" class="btn-warning"
                        :disabled="selectedEncryptMethod === securityInfo.encryptMethod">
                  更改加密方式
                </button>
              </div>
            </div>
          </div>

          <!-- 设备管理 -->
          <div class="security-section">
            <h3>📱 设备管理</h3>
            <div class="security-card">
              <div class="card-header">
                <h4>已登录设备</h4>
                <span class="status-badge">{{ userDevices.length }} 台设备</span>
              </div>
              <p>管理已登录的设备，及时清理不安全的登录</p>
              <div class="devices-list">
                <div v-for="device in userDevices" :key="device.id" class="device-item">
                  <div class="device-info">
                    <div class="device-name">
                      <span class="device-icon">{{ getDeviceIcon(device.platform) }}</span>
                      {{ device.device_name || `${device.platform} 设备` }}
                    </div>
                    <div class="device-details">
                      <span>{{ device.platform }} • IP: {{ device.ip_address }}</span>
                      <span>最后活跃：{{ formatTime(device.last_active) }}</span>
                    </div>
                  </div>
                  <div class="device-actions">
                    <span v-if="device.is_current" class="current-device">当前设备</span>
                    <button v-else @click="removeDevice(device.id)" class="btn-danger-text">移除</button>
                  </div>
                </div>
              </div>
              <button @click="loadUserDevices" class="btn-secondary">刷新设备列表</button>
            </div>
          </div>

          <!-- 生物识别 -->
          <div class="security-section">
            <h3>🔬 生物识别</h3>
            <div class="security-card">
              <div class="card-header">
                <h4>指纹/面容识别</h4>
                <span class="status-badge" :class="securityInfo.biometricEnabled ? 'good' : 'warning'">
                  {{ securityInfo.biometricEnabled ? '已启用' : '未启用' }}
                </span>
              </div>
              <p>使用指纹或面容识别快速解锁应用</p>
              <div class="biometric-controls">
                <button v-if="!securityInfo.biometricEnabled" @click="enableBiometric" class="btn-primary">
                  启用生物识别
                </button>
                <button v-else @click="disableBiometric" class="btn-secondary">
                  禁用生物识别
                </button>
              </div>
            </div>
          </div>

          <!-- 安全日志 -->
          <div class="security-section">
            <h3>📋 安全日志</h3>
            <div class="security-card">
              <div class="card-header">
                <h4>最近安全活动</h4>
                <button @click="loadSecurityLogs" class="btn-text">查看全部</button>
              </div>
              <div class="security-logs">
                <div v-for="log in securityLogs" :key="log.id" class="log-item">
                  <div class="log-icon">{{ getLogIcon(log.action) }}</div>
                  <div class="log-content">
                    <div class="log-action">{{ log.description }}</div>
                    <div class="log-time">{{ formatTime(log.created_at) }} • {{ log.ip }}</div>
                  </div>
                </div>
              </div>
            </div>
          </div>
        </div>

        <!-- 个人资料 -->
        <div v-if="activeTab === 'profile'" class="tab-content">
          <h2>{{ $t('nav.profile') }}</h2>

          <!-- 基本信息 -->
          <div class="profile-section">
            <h3>👤 基本信息</h3>
            <div class="profile-card">
              <div class="avatar-section">
                <div class="avatar-container">
                  <img v-if="userInfo.avatar" :src="userInfo.avatar" alt="头像" class="avatar">
                  <div v-else class="avatar-placeholder">
                    {{ userInfo.nickname?.charAt(0) || userInfo.username?.charAt(0) || '用' }}
                  </div>
                  <button @click="changeAvatar" class="avatar-change-btn">更换头像</button>
                </div>
              </div>

              <div class="profile-form">
                <div class="form-group">
                  <label>用户名</label>
                  <input v-model="userInfo.username" class="form-input" readonly>
                  <small class="form-help">用户名不可修改</small>
                </div>

                <div class="form-group">
                  <label>昵称</label>
                  <input v-model="profileForm.nickname" class="form-input" placeholder="请输入昵称">
                </div>

                <div class="form-group">
                  <label>邮箱</label>
                  <input v-model="profileForm.email" type="email" class="form-input" placeholder="请输入邮箱">
                  <div v-if="userInfo.email && !userInfo.email_verified" class="form-warning">
                    邮箱未验证 <button @click="sendEmailVerification" class="btn-text">发送验证邮件</button>
                  </div>
                </div>

                <div class="form-group">
                  <label>手机号</label>
                  <input v-model="profileForm.phone" class="form-input" placeholder="请输入手机号">
                  <div v-if="userInfo.phone && !userInfo.phone_verified" class="form-warning">
                    手机号未验证 <button @click="sendPhoneVerification" class="btn-text">发送验证短信</button>
                  </div>
                </div>

                <div class="form-actions">
                  <button @click="updateProfile" class="btn-primary" :disabled="!isProfileChanged">
                    保存更改
                  </button>
                  <button @click="resetProfileForm" class="btn-secondary">重置</button>
                </div>
              </div>
            </div>
          </div>

          <!-- 账号绑定 -->
          <div class="profile-section">
            <h3>🔗 账号绑定</h3>
            <div class="profile-card">
              <div class="binding-list">
                <div v-for="binding in accountBindings" :key="binding.platform" class="binding-item">
                  <div class="binding-info">
                    <div class="binding-icon">{{ getPlatformIcon(binding.platform) }}</div>
                    <div class="binding-details">
                      <div class="binding-name">{{ getPlatformName(binding.platform) }}</div>
                      <div class="binding-status">
                        <span v-if="binding.bound" class="bound-status">
                          已绑定 • {{ binding.nickname || binding.openid }}
                        </span>
                        <span v-else class="unbound-status">未绑定</span>
                      </div>
                    </div>
                  </div>
                  <div class="binding-actions">
                    <button v-if="binding.bound" @click="unbindAccount(binding.platform)" class="btn-danger-text">
                      解绑
                    </button>
                    <button v-else @click="bindAccount(binding.platform)" class="btn-primary">
                      绑定
                    </button>
                  </div>
                </div>
              </div>
            </div>
          </div>

          <!-- 使用统计 -->
          <div class="profile-section">
            <h3>📊 使用统计</h3>
            <div class="profile-card">
              <div class="stats-grid">
                <div class="stat-item">
                  <div class="stat-label">注册时间</div>
                  <div class="stat-value">{{ formatTime(userInfo.created_at) }}</div>
                </div>
                <div class="stat-item">
                  <div class="stat-label">最后登录</div>
                  <div class="stat-value">{{ formatTime(userInfo.last_login_at) }}</div>
                </div>
                <div class="stat-item">
                  <div class="stat-label">总账号数</div>
                  <div class="stat-value">{{ userStats.totalAccounts || 0 }}</div>
                </div>
                <div class="stat-item">
                  <div class="stat-label">总分类数</div>
                  <div class="stat-value">{{ userStats.totalCategories || 0 }}</div>
                </div>
                <div class="stat-item">
                  <div class="stat-label">登录设备</div>
                  <div class="stat-value">{{ userStats.totalDevices || 0 }}</div>
                </div>
                <div class="stat-item">
                  <div class="stat-label">操作次数</div>
                  <div class="stat-value">{{ userStats.totalOperations || 0 }}</div>
                </div>
              </div>
            </div>
          </div>

          <!-- 数据管理 -->
          <div class="profile-section">
            <h3>💾 数据管理</h3>
            <div class="profile-card">
              <div class="data-actions">
                <div class="action-item">
                  <div class="action-info">
                    <h4>导出数据</h4>
                    <p>导出所有账号数据为JSON或CSV文件</p>
                  </div>
                  <button @click="exportData" class="btn-secondary">导出</button>
                </div>
                <div class="action-item">
                  <div class="action-info">
                    <h4>导入数据</h4>
                    <p>从备份文件导入账号数据</p>
                  </div>
                  <div style="display: flex; gap: 8px;">
                    <button @click="importData" class="btn-secondary">导入文件</button>
                  </div>
                </div>
                <div class="action-item">
                  <div class="action-info">
                    <h4>创建备份</h4>
                    <p>创建当前数据的备份快照</p>
                  </div>
                  <div style="display: flex; gap: 8px;">
                    <button @click="createBackupNow" class="btn-primary">立即备份</button>
                    <button @click="manageBackups" class="btn-secondary">管理备份</button>
                  </div>
                </div>
                <div class="action-item">
                  <div class="action-info">
                    <h4>清空数据</h4>
                    <p>删除所有账号数据（不可恢复）</p>
                  </div>
                  <button @click="clearAllData" class="btn-danger">清空</button>
                </div>
                <div class="action-item">
                  <div class="action-info">
                    <h4>注销账户</h4>
                    <p>永久删除账户和所有相关数据</p>
                  </div>
                  <button @click="deleteUserAccount" class="btn-danger">注销账户</button>
                </div>
              </div>
            </div>
          </div>
        </div>
      </section>
    </main>

    <!-- 账号表单弹窗 -->
    <AccountForm
      :visible="showAccountForm"
      :is-edit="isEditMode"
      :account="currentAccount"
      :categories="categories"
      @close="closeAccountForm"
      @save="saveAccount"
    />

    <!-- 修改主密码弹窗 -->
    <div v-if="showChangePasswordModal" class="modal-overlay" @click="cancelPasswordChange">
      <div class="modal-content password-change-wizard" @click.stop>
        <div class="modal-header">
          <h3>修改主密码</h3>
          <button @click="cancelPasswordChange" class="modal-close">×</button>
        </div>

        <!-- 步骤指示器 -->
        <div class="wizard-steps">
          <div class="wizard-step" :class="{ active: passwordChangeStep === 1, completed: passwordChangeStep > 1 }">
            <div class="step-number">1</div>
            <div class="step-label">设置密码</div>
          </div>
          <div class="wizard-line" :class="{ active: passwordChangeStep > 1 }"></div>
          <div class="wizard-step" :class="{ active: passwordChangeStep === 2, completed: passwordChangeStep > 2 }">
            <div class="step-number">2</div>
            <div class="step-label">确认信息</div>
          </div>
          <div class="wizard-line" :class="{ active: passwordChangeStep > 2 }"></div>
          <div class="wizard-step" :class="{ active: passwordChangeStep === 3 }">
            <div class="step-number">3</div>
            <div class="step-label">处理中</div>
          </div>
        </div>

        <div class="modal-body">
          <!-- 步骤1: 填写密码 -->
          <div v-if="passwordChangeStep === 1" class="wizard-content">
            <div class="form-group">
              <label>当前主密码</label>
              <input v-model="passwordForm.currentPassword" type="password" class="form-input" placeholder="请输入当前主密码">
            </div>
            <div class="form-group">
              <label>新主密码</label>
              <input v-model="passwordForm.newPassword" type="password" class="form-input" placeholder="请输入新主密码(至少8位)">
              <PasswordStrengthMeter v-if="passwordForm.newPassword" :password="passwordForm.newPassword" :showScore="true" />
            </div>
            <div class="form-group">
              <label>确认新密码</label>
              <input v-model="passwordForm.confirmPassword" type="password" class="form-input" placeholder="请再次输入新主密码">
              <div v-if="passwordForm.confirmPassword && passwordForm.newPassword !== passwordForm.confirmPassword" class="error-message">
                两次输入的密码不一致
              </div>
              <div v-else-if="passwordForm.confirmPassword && passwordForm.newPassword === passwordForm.confirmPassword" class="success-message">
                ✓ 密码一致
              </div>
            </div>
            <div class="form-group">
              <label>密码提示</label>
              <input v-model="passwordForm.hint" class="form-input" placeholder="可选：设置密码提示">
            </div>
          </div>

          <!-- 步骤2: 确认信息 -->
          <div v-if="passwordChangeStep === 2" class="wizard-content">
            <div class="info-box warning">
              <h4>⚠️ 重要提示</h4>
              <p>修改主密码将会重新加密所有账号数据，这需要一些时间。</p>
            </div>
            <div class="info-stats">
              <div class="stat-item">
                <div class="stat-label">需要重新加密的账号数</div>
                <div class="stat-value">{{ accounts.length }} 个</div>
              </div>
              <div class="stat-item">
                <div class="stat-label">预计耗时</div>
                <div class="stat-value">{{ estimatedTime }} 秒</div>
              </div>
            </div>
            <div class="info-box info">
              <p>💡 <strong>提示：</strong>请确保在处理完成前不要关闭页面</p>
            </div>
          </div>

          <!-- 步骤3: 处理中 -->
          <div v-if="passwordChangeStep === 3" class="wizard-content">
            <div class="processing-container">
              <div class="progress-circle">
                <svg width="120" height="120">
                  <circle cx="60" cy="60" r="54" fill="none" stroke="#e8e8e8" stroke-width="8"/>
                  <circle
                    cx="60" cy="60" r="54" fill="none"
                    stroke="#1890ff"
                    stroke-width="8"
                    stroke-dasharray="339.292"
                    :stroke-dashoffset="339.292 * (1 - reencryptProgress / 100)"
                    transform="rotate(-90 60 60)"
                    style="transition: stroke-dashoffset 0.3s ease;"
                  />
                </svg>
                <div class="progress-text">{{ reencryptProgress }}%</div>
              </div>
              <h4 class="processing-title">正在重新加密数据...</h4>
              <p class="processing-info">已处理 {{ reencryptedCount }} / {{ accounts.length }} 个账号</p>
              <div class="progress-bar-container">
                <div class="progress-bar-fill" :style="{ width: reencryptProgress + '%' }"></div>
              </div>
            </div>
          </div>
        </div>

        <div class="modal-footer">
          <button
            v-if="passwordChangeStep < 3"
            @click="cancelPasswordChange"
            class="btn-secondary"
          >
            取消
          </button>
          <button
            v-if="passwordChangeStep === 2"
            @click="passwordChangeStep = 1"
            class="btn-secondary"
          >
            上一步
          </button>
          <button
            v-if="passwordChangeStep < 3"
            @click="changeMasterPassword"
            class="btn-primary"
            :disabled="passwordChangeStep === 1 && (!passwordForm.currentPassword || !passwordForm.newPassword || passwordForm.newPassword !== passwordForm.confirmPassword || passwordForm.newPassword.length < 8)"
          >
            {{ passwordChangeStep === 1 ? '下一步' : '开始修改' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 修改登录密码弹窗 -->
    <div v-if="showChangeLoginPasswordModal" class="modal-overlay" @click="showChangeLoginPasswordModal = false">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>修改登录密码</h3>
          <button @click="showChangeLoginPasswordModal = false" class="modal-close">×</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>当前密码</label>
            <input v-model="loginPasswordForm.currentPassword" type="password" class="form-input" placeholder="请输入当前登录密码">
          </div>
          <div class="form-group">
            <label>新密码</label>
            <input v-model="loginPasswordForm.newPassword" type="password" class="form-input" placeholder="请输入新密码">
          </div>
          <div class="form-group">
            <label>确认新密码</label>
            <input v-model="loginPasswordForm.confirmPassword" type="password" class="form-input" placeholder="请再次输入新密码">
          </div>
        </div>
        <div class="modal-footer">
          <button @click="showChangeLoginPasswordModal = false" class="btn-secondary">取消</button>
          <button @click="changeLoginPassword" class="btn-primary">确认修改</button>
        </div>
      </div>
    </div>

    <!-- 主密码验证模态框 -->
    <div v-if="showMasterPasswordModal" class="modal-overlay" @click="showMasterPasswordModal = false">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>验证主密码</h3>
          <button @click="showMasterPasswordModal = false" class="modal-close">×</button>
        </div>
        <div class="modal-body">
          <p style="color: #666; margin-bottom: 16px;">为了保护您的数据安全，请输入主密码来解密账号信息</p>
          <div class="form-group">
            <label>主密码</label>
            <input v-model="masterPasswordInput" type="password" class="form-input" placeholder="请输入主密码" @keyup.enter="verifyMasterPassword">
          </div>
          <div class="form-group" style="margin-top: 12px;">
            <label style="display: flex; align-items: center; cursor: pointer; user-select: none;">
              <input v-model="rememberMasterPassword" type="checkbox" style="margin-right: 8px; cursor: pointer;">
              <span style="font-size: 14px; color: #666;">此次登录不再验证主密码（30分钟内有效）</span>
            </label>
          </div>
          <div v-if="masterPasswordError" class="error-message">{{ masterPasswordError }}</div>
        </div>
        <div class="modal-footer">
          <button @click="showMasterPasswordModal = false" class="btn-secondary">取消</button>
          <button @click="verifyMasterPassword" class="btn-primary" :disabled="!masterPasswordInput">确认</button>
        </div>
      </div>
    </div>

    <!-- 账号详情模态框 -->
    <div v-if="showAccountDetailModal" class="modal-overlay" @click="showAccountDetailModal = false">
      <div class="modal-content large-modal" @click.stop>
        <div class="modal-header">
          <h3>{{ decryptedAccount?.title }} - 账号详情</h3>
          <button @click="showAccountDetailModal = false" class="modal-close">×</button>
        </div>
        <div class="modal-body">
          <div v-if="decryptedAccount" class="account-details">
            <div class="detail-row">
              <label>网站/平台:</label>
              <span class="detail-value">{{ decryptedAccount.website || '未设置' }}</span>
            </div>
            <div class="detail-row">
              <label>用户名:</label>
              <div class="detail-value-with-copy">
                <span class="detail-value">{{ decryptedAccount.username || '未设置' }}</span>
                <button v-if="decryptedAccount.username" @click="copyToClipboard(decryptedAccount.username)" class="copy-btn">📋</button>
              </div>
            </div>
            <div class="detail-row">
              <label>密码:</label>
              <div class="detail-value-with-copy">
                <span class="detail-value password-field" :class="{ 'password-hidden': !showPassword }">
                  {{ showPassword ? (decryptedAccount.password || '未设置') : '●●●●●●●●' }}
                </span>
                <button @click="togglePasswordVisibility" class="copy-btn">{{ showPassword ? '🙈' : '👁️' }}</button>
                <button v-if="decryptedAccount.password" @click="copyToClipboard(decryptedAccount.password)" class="copy-btn">📋</button>
              </div>
            </div>
            <div class="detail-row">
              <label>备注:</label>
              <span class="detail-value">{{ decryptedAccount.notes || '无备注' }}</span>
            </div>
            <div class="detail-row">
              <label>分类:</label>
              <span class="detail-value">{{ decryptedAccount.category?.name || '未分类' }}</span>
            </div>
            <div class="detail-row">
              <label>创建时间:</label>
              <span class="detail-value">{{ formatTime(decryptedAccount.created_at) }}</span>
            </div>
            <div class="detail-row">
              <label>最后修改:</label>
              <span class="detail-value">{{ formatTime(decryptedAccount.updated_at) }}</span>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="editDecryptedAccount" class="btn-primary">编辑</button>
          <button @click="showAccountDetailModal = false" class="btn-secondary">关闭</button>
        </div>
      </div>
    </div>

    <!-- 导出数据模态框 -->
    <div v-if="showImportExportModal" class="modal-overlay" @click="showImportExportModal = false">
      <div class="modal-content" @click.stop>
        <div class="modal-header">
          <h3>导出数据</h3>
          <button @click="showImportExportModal = false" class="modal-close">×</button>
        </div>
        <div class="modal-body">
          <div class="form-group">
            <label>选择导出格式</label>
            <div class="export-format-options">
              <label class="format-option">
                <input type="radio" v-model="exportFormat" value="json" name="export-format">
                <div class="format-card">
                  <div class="format-icon">📄</div>
                  <div class="format-name">JSON格式</div>
                  <div class="format-desc">完整数据,包含加密信息,适合备份</div>
                </div>
              </label>
              <label class="format-option">
                <input type="radio" v-model="exportFormat" value="csv" name="export-format">
                <div class="format-card">
                  <div class="format-icon">📊</div>
                  <div class="format-name">CSV格式</div>
                  <div class="format-desc">简化数据,不含敏感信息,适合查看</div>
                </div>
              </label>
            </div>
          </div>
          <div class="export-tips">
            <p><strong>提示:</strong></p>
            <ul>
              <li>JSON格式包含完整加密数据,可用于完整恢复</li>
              <li>CSV格式仅包含基本信息,不含密码等敏感数据</li>
              <li>导出的文件请妥善保管,避免泄露</li>
            </ul>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="showImportExportModal = false" class="btn-secondary">取消</button>
          <button @click="performExport" class="btn-primary" :disabled="isExporting">
            {{ isExporting ? '导出中...' : '开始导出' }}
          </button>
        </div>
      </div>
    </div>

    <!-- 备份管理模态框 -->
    <div v-if="showBackupModal" class="modal-overlay" @click="showBackupModal = false">
      <div class="modal-content large-modal" @click.stop>
        <div class="modal-header">
          <h3>备份管理</h3>
          <button @click="showBackupModal = false" class="modal-close">×</button>
        </div>
        <div class="modal-body">
          <div v-if="backupList.length === 0" class="empty-state">
            <div class="empty-icon">📦</div>
            <div class="empty-text">暂无备份</div>
            <button @click="createBackupNow" class="btn-primary" style="margin-top: 16px;">创建第一个备份</button>
          </div>
          <div v-else class="backup-list">
            <div v-for="backup in backupList" :key="backup.filename" class="backup-item">
              <div class="backup-info">
                <div class="backup-icon">💾</div>
                <div class="backup-details">
                  <div class="backup-name">{{ backup.filename }}</div>
                  <div class="backup-meta">
                    <span>{{ formatFileSize(backup.size) }}</span>
                    <span>•</span>
                    <span>{{ formatTime(backup.created_at) }}</span>
                  </div>
                </div>
              </div>
              <div class="backup-actions">
                <button @click="restoreBackupFile(backup.filename)" class="btn-primary" style="padding: 6px 12px; font-size: 13px;">
                  恢复
                </button>
                <button @click="deleteBackupFile(backup.filename)" class="btn-danger-text">
                  删除
                </button>
              </div>
            </div>
          </div>
        </div>
        <div class="modal-footer">
          <button @click="createBackupNow" class="btn-primary">创建新备份</button>
          <button @click="showBackupModal = false" class="btn-secondary">关闭</button>
        </div>
      </div>
    </div>

    <!-- 导入进度提示 -->
    <div v-if="isImporting" class="import-progress-overlay">
      <div class="import-progress-card">
        <div class="progress-icon">📥</div>
        <div class="progress-text">正在导入数据...</div>
        <div class="progress-bar">
          <div class="progress-fill" :style="{ width: importProgress + '%' }"></div>
        </div>
        <div class="progress-percent">{{ importProgress }}%</div>
      </div>
    </div>

    <!-- Toast提示 -->
    <Toast
      :visible="toastVisible"
      :type="toastType"
      :message="toastMessage"
    />
  </div>
</template>

<script setup lang="ts">
import { ref, onMounted, onUnmounted, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useI18n } from 'vue-i18n'
import AccountForm from '../components/AccountForm.vue'
import Toast from '../components/Toast.vue'
import PasswordStrengthMeter from '../components/PasswordStrengthMeter.vue'
import PasswordGeneratorModal from '../components/PasswordGeneratorModal.vue'
import { createCrypto, EncryptMethod } from '@/utils/crypto'
import { MasterPasswordSession } from '@/utils/master-password'
import { useTheme } from '@/composables/useTheme'
import { switchLocale, getCurrentLocale, type Locale } from '@/i18n'

const router = useRouter()
const { t } = useI18n()

// 主题管理
const { initTheme, toggleTheme: themeToggle, isDark: themeIsDark } = useTheme()

// 国际化管理
const currentLocale = ref<Locale>(getCurrentLocale())

// 主题控制函数（供模板使用）
const toggleTheme = () => {
  themeToggle()
  const mode = themeIsDark() ? t('theme.dark') : t('theme.light')
  showToast('success', t('theme.switched', { mode }))
}

const isDark = () => themeIsDark()

// 语言切换函数
const toggleLanguage = () => {
  const newLocale: Locale = currentLocale.value === 'zh-CN' ? 'en-US' : 'zh-CN'
  switchLocale(newLocale)
  currentLocale.value = newLocale
  showToast('success', `Language switched to ${newLocale === 'zh-CN' ? '简体中文' : 'English'}`)
}

// 响应式数据
const activeTab = ref('overview')
const userInfo = ref({
  id: 1,
  username: 'admin',
  nickname: '管理员',
  email: '',
  phone: '',
  avatar: '',
  email_verified: false,
  phone_verified: false,
  created_at: '',
  last_login_at: ''
})

const stats = ref({
  totalAccounts: 0,
  totalCategories: 0,
  favoriteAccounts: 0,
  expiringAccounts: 0
})

const accounts = ref([])
const categories = ref([])
const recentAccounts = ref([])
const searchQuery = ref('')
const filterCategory = ref('')
const isLoadingAccounts = ref(false)
const isLoadingCategories = ref(false)
const isLoadingStats = ref(false)

// 高级搜索
const showAdvancedSearch = ref(false)
const advancedSearchFilters = ref({
  keyword: '',
  category: '',
  website: '',
  username: '',
  dateFrom: '',
  dateTo: '',
  hasExpiry: null as boolean | null,
  isFavorite: null as boolean | null
})
const searchHistory = ref<string[]>([])

// 批量操作
const batchMode = ref(false)
const selectedAccounts = ref<number[]>([])
const isAllSelected = computed(() => {
  return selectedAccounts.value.length > 0 &&
         selectedAccounts.value.length === filteredAccounts.value.length
})
const isIndeterminate = computed(() => {
  return selectedAccounts.value.length > 0 &&
         selectedAccounts.value.length < filteredAccounts.value.length
})

// 安全设置相关
const securityInfo = ref({
  masterPasswordLastChanged: '',
  loginPasswordLastChanged: '',
  encryptMethod: 'AES-256-GCM',
  biometricEnabled: false
})

const userDevices = ref([])
const securityLogs = ref([])
const encryptMethods = ref([])
const selectedEncryptMethod = ref('AES-256-GCM')

// 个人资料相关
const profileForm = ref({
  nickname: '',
  email: '',
  phone: ''
})

const userStats = ref({
  totalAccounts: 0,
  totalCategories: 0,
  totalDevices: 0,
  totalOperations: 0
})

const accountBindings = ref([
  { platform: 'wechat', bound: false, nickname: '', openid: '' },
  { platform: 'alipay', bound: false, nickname: '', openid: '' },
  { platform: 'douyin', bound: false, nickname: '', openid: '' }
])

// 弹窗状态
const showChangePasswordModal = ref(false)
const showChangeLoginPasswordModal = ref(false)

// 密码表单
const passwordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: '',
  hint: ''
})

const loginPasswordForm = ref({
  currentPassword: '',
  newPassword: '',
  confirmPassword: ''
})

// 表单相关
const showAccountForm = ref(false)
const isEditMode = ref(false)
const currentAccount = ref(null)

// Toast相关
const toastVisible = ref(false)
const toastType = ref<'success' | 'error' | 'warning' | 'info'>('info')
const toastMessage = ref('')

// 主密码验证相关
const showMasterPasswordModal = ref(false)
const showAccountDetailModal = ref(false)
const masterPasswordInput = ref('')
const masterPasswordError = ref('')
const rememberMasterPassword = ref(false)
const pendingAccountForView = ref(null)
const decryptedAccount = ref(null)
const showPassword = ref(false)

// 计算属性
const filteredAccounts = computed(() => {
  let filtered = accounts.value

  // 基础搜索
  if (searchQuery.value && !showAdvancedSearch.value) {
    const query = searchQuery.value.toLowerCase()
    filtered = filtered.filter(account =>
      (account.title || account.name || '').toLowerCase().includes(query) ||
      (account.website && account.website.toLowerCase().includes(query))
    )
  }

  // 高级搜索
  if (showAdvancedSearch.value) {
    const filters = advancedSearchFilters.value

    // 关键词（模糊搜索：标题、网站、备注）
    if (filters.keyword) {
      const keyword = filters.keyword.toLowerCase()
      filtered = filtered.filter(account =>
        (account.title || account.name || '').toLowerCase().includes(keyword) ||
        (account.website && account.website.toLowerCase().includes(keyword)) ||
        (account.notes && account.notes.toLowerCase().includes(keyword))
      )
    }

    // 分类筛选
    if (filters.category) {
      filtered = filtered.filter(account => account.category?.name === filters.category)
    }

    // 网站筛选
    if (filters.website) {
      const website = filters.website.toLowerCase()
      filtered = filtered.filter(account =>
        account.website && account.website.toLowerCase().includes(website)
      )
    }

    // 用户名筛选（需要解密，这里只做简单包含判断）
    if (filters.username) {
      const username = filters.username.toLowerCase()
      filtered = filtered.filter(account =>
        account.username && account.username.toLowerCase().includes(username)
      )
    }

    // 日期范围筛选
    if (filters.dateFrom) {
      filtered = filtered.filter(account =>
        new Date(account.created_at) >= new Date(filters.dateFrom)
      )
    }

    if (filters.dateTo) {
      filtered = filtered.filter(account =>
        new Date(account.created_at) <= new Date(filters.dateTo)
      )
    }

    // 是否有过期时间
    if (filters.hasExpiry !== null) {
      filtered = filtered.filter(account =>
        filters.hasExpiry ? !!account.expiry_date : !account.expiry_date
      )
    }

    // 是否收藏
    if (filters.isFavorite !== null) {
      filtered = filtered.filter(account =>
        filters.isFavorite ? !!account.is_favorite : !account.is_favorite
      )
    }
  }

  // 基础分类筛选（与高级搜索分开）
  if (filterCategory.value && !showAdvancedSearch.value) {
    filtered = filtered.filter(account => account.category?.name === filterCategory.value)
  }

  return filtered
})

// 个人资料是否有变更
const isProfileChanged = computed(() => {
  return profileForm.value.nickname !== userInfo.value.nickname ||
         profileForm.value.email !== userInfo.value.email ||
         profileForm.value.phone !== userInfo.value.phone
})

// 页面加载
// 快捷键处理
const handleKeyboard = (e: KeyboardEvent) => {
  // Ctrl/Cmd + N: 新建账号
  if ((e.ctrlKey || e.metaKey) && e.key === 'n') {
    e.preventDefault()
    if (activeTab.value === 'accounts') {
      addAccount()
      showToast('info', '快捷键: Ctrl+N - 新建账号')
    }
  }

  // Ctrl/Cmd + F: 聚焦搜索框
  if ((e.ctrlKey || e.metaKey) && e.key === 'f') {
    e.preventDefault()
    if (activeTab.value === 'accounts') {
      const searchInput = document.querySelector('.search-input') as HTMLInputElement
      if (searchInput) {
        searchInput.focus()
        showToast('info', '快捷键: Ctrl+F - 搜索')
      }
    }
  }

  // Ctrl/Cmd + E: 导出数据
  if ((e.ctrlKey || e.metaKey) && e.key === 'e') {
    e.preventDefault()
    if (activeTab.value === 'import-export') {
      showToast('info', '快捷键: Ctrl+E - 导出数据')
    }
  }

  // Esc: 关闭弹窗
  if (e.key === 'Escape') {
    if (showAccountForm.value) {
      showAccountForm.value = false
      showToast('info', '快捷键: Esc - 关闭弹窗')
    } else if (showCategoryForm.value) {
      showCategoryForm.value = false
    } else if (showChangePasswordModal.value) {
      cancelPasswordChange()
    } else if (showChangeLoginPasswordModal.value) {
      showChangeLoginPasswordModal.value = false
    }
  }

  // Ctrl/Cmd + 1-6: 快速切换标签页
  if ((e.ctrlKey || e.metaKey) && e.key >= '1' && e.key <= '6') {
    e.preventDefault()
    const tabs = ['overview', 'accounts', 'notifications', 'statistics', 'import-export', 'profile']
    const index = parseInt(e.key) - 1
    if (index < tabs.length) {
      activeTab.value = tabs[index]
      showToast('info', `快捷键: Ctrl+${e.key} - 切换到标签页`)
    }
  }
}

onMounted(() => {
  // 初始化主题
  initTheme()

  loadUserInfo()
  loadStats()
  loadAccounts()
  loadCategories()
  loadNotifications()
  loadStatistics()
  loadEncryptMethods()
  loadUserDevices()
  loadSecurityLogs()

  // 初始化个人资料表单
  profileForm.value = {
    nickname: userInfo.value.nickname,
    email: userInfo.value.email,
    phone: userInfo.value.phone
  }

  // 加载搜索历史
  const history = localStorage.getItem('searchHistory')
  if (history) {
    searchHistory.value = JSON.parse(history)
  }

  // 注册快捷键
  window.addEventListener('keydown', handleKeyboard)
})

// 组件卸载时移除事件监听
onUnmounted(() => {
  window.removeEventListener('keydown', handleKeyboard)
})

// Toast函数
const showToast = (type: 'success' | 'error' | 'warning' | 'info', message: string) => {
  toastType.value = type
  toastMessage.value = message
  toastVisible.value = true

  // 3秒后自动隐藏
  setTimeout(() => {
    toastVisible.value = false
  }, 3000)
}

// 设置活跃标签
const setActiveTab = (tab: string) => {
  activeTab.value = tab
}

// 高级搜索函数
const toggleAdvancedSearch = () => {
  showAdvancedSearch.value = !showAdvancedSearch.value
  if (!showAdvancedSearch.value) {
    resetAdvancedFilters()
  }
}

const resetAdvancedFilters = () => {
  advancedSearchFilters.value = {
    keyword: '',
    category: '',
    website: '',
    username: '',
    dateFrom: '',
    dateTo: '',
    hasExpiry: null,
    isFavorite: null
  }
}

const applyAdvancedSearch = () => {
  // 添加到搜索历史
  if (advancedSearchFilters.value.keyword && !searchHistory.value.includes(advancedSearchFilters.value.keyword)) {
    searchHistory.value.unshift(advancedSearchFilters.value.keyword)
    if (searchHistory.value.length > 5) {
      searchHistory.value = searchHistory.value.slice(0, 5)
    }
    localStorage.setItem('searchHistory', JSON.stringify(searchHistory.value))
  }
  showToast('success', `找到 ${filteredAccounts.value.length} 个匹配结果`)
}

const useSearchHistory = (keyword: string) => {
  advancedSearchFilters.value.keyword = keyword
  applyAdvancedSearch()
}

// 批量操作函数
const toggleBatchMode = () => {
  batchMode.value = !batchMode.value
  if (!batchMode.value) {
    selectedAccounts.value = []
  }
}

const toggleSelectAll = () => {
  if (isAllSelected.value) {
    selectedAccounts.value = []
  } else {
    selectedAccounts.value = filteredAccounts.value.map((account: any) => account.id)
  }
}

const toggleSelectAccount = (accountId: number) => {
  const index = selectedAccounts.value.indexOf(accountId)
  if (index > -1) {
    selectedAccounts.value.splice(index, 1)
  } else {
    selectedAccounts.value.push(accountId)
  }
}

const batchDeleteAccounts = async () => {
  if (selectedAccounts.value.length === 0) {
    showToast('warning', '请至少选择一个账号')
    return
  }

  if (!confirm(`确定要删除选中的 ${selectedAccounts.value.length} 个账号吗？`)) {
    return
  }

  const masterPassword = prompt('请输入主密码以确认删除：')
  if (!masterPassword) return

  try {
    const response = await fetch('/api/accounts/batch-delete', {
      method: 'POST',
      headers: getAuthHeaders(),
      body: JSON.stringify({
        account_ids: selectedAccounts.value,
        master_password: masterPassword
      })
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        showToast('success', `成功删除 ${selectedAccounts.value.length} 个账号`)
        selectedAccounts.value = []
        batchMode.value = false
        loadAccounts()
      } else {
        showToast('error', result.message)
      }
    }
  } catch (error) {
    console.error('批量删除失败:', error)
    showToast('error', '批量删除失败，请重试')
  }
}

const batchExportAccounts = async () => {
  if (selectedAccounts.value.length === 0) {
    showToast('warning', '请至少选择一个账号')
    return
  }

  try {
    const response = await fetch('/api/import/export-json', {
      method: 'POST',
      headers: getAuthHeaders(),
      body: JSON.stringify({
        account_ids: selectedAccounts.value
      })
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        const { exportToJsonFile } = await import('@/utils/import-export')
        exportToJsonFile(result.data, `账号数据_${selectedAccounts.value.length}个_${Date.now()}.json`)
        showToast('success', `成功导出 ${selectedAccounts.value.length} 个账号`)
      }
    }
  } catch (error) {
    console.error('批量导出失败:', error)
    showToast('error', '批量导出失败，请重试')
  }
}

const batchMoveCategory = async (categoryId: number) => {
  if (selectedAccounts.value.length === 0) {
    showToast('warning', '请至少选择一个账号')
    return
  }

  try {
    const promises = selectedAccounts.value.map(accountId =>
      fetch(`/api/accounts/${accountId}`, {
        method: 'PUT',
        headers: getAuthHeaders(),
        body: JSON.stringify({
          category_id: categoryId
        })
      })
    )

    await Promise.all(promises)
    showToast('success', `成功移动 ${selectedAccounts.value.length} 个账号`)
    selectedAccounts.value = []
    batchMode.value = false
    loadAccounts()
  } catch (error) {
    console.error('批量移动失败:', error)
    showToast('error', '批量移动失败，请重试')
  }
}

// 加载用户信息
const loadUserInfo = () => {
  // 从localStorage获取用户信息
  const user = localStorage.getItem('userInfo')
  if (user) {
    userInfo.value = JSON.parse(user)
  }
}

// 获取认证头
const getAuthHeaders = () => {
  const token = localStorage.getItem('token')
  return {
    'Content-Type': 'application/json',
    'Authorization': `Bearer ${token}`
  }
}

// 加载统计数据
const loadStats = async () => {
  try {
    const response = await fetch('/api/accounts/stats', {
      headers: getAuthHeaders()
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        stats.value = result.data
      }
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
    // 使用模拟数据作为fallback
    stats.value = {
      totalAccounts: accounts.value.length,
      totalCategories: categories.value.length,
      favoriteAccounts: 0,
      expiringAccounts: 0
    }
  }
}

// 加载账号列表
const loadAccounts = async () => {
  isLoadingAccounts.value = true
  try {
    const response = await fetch('/api/accounts', {
      headers: getAuthHeaders()
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        accounts.value = result.data
        recentAccounts.value = accounts.value.slice(-3).reverse()
        console.log('账号数据样例:', result.data.slice(0, 2))
        console.log('第一个账号的分类信息:', result.data[0]?.category)
      }
    } else {
      console.error('加载账号列表失败:', response.status)
    }
  } catch (error) {
    console.error('加载账号列表失败:', error)
    // 使用模拟数据作为fallback
    accounts.value = []
    recentAccounts.value = []
  } finally {
    isLoadingAccounts.value = false
  }
}

// 加载分类列表
const loadCategories = async () => {
  isLoadingCategories.value = true
  try {
    const response = await fetch('/api/categories', {
      headers: getAuthHeaders()
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        categories.value = result.data
        console.log('分类加载成功:', result.data)
      } else {
        console.error('分类API返回错误:', result)
        showToast('error', '分类加载失败: ' + result.message)
      }
    } else {
      console.error('分类API请求失败:', response.status)
      if (response.status === 401) {
        showToast('error', '登录已过期，请重新登录')
      } else {
        showToast('error', '分类加载失败')
      }
    }
  } catch (error) {
    console.error('分类加载异常:', error)
    showToast('error', '分类加载失败，请检查网络连接')
    // 使用模拟数据作为fallback
    categories.value = [
      { id: 1, name: '开发工具', description: '编程相关的账号' },
      { id: 2, name: '社交媒体', description: '社交平台账号' },
      { id: 3, name: '云服务', description: '云计算服务' }
    ]
  } finally {
    isLoadingCategories.value = false
  }
}

// 账号操作
const addAccount = () => {
  isEditMode.value = false
  currentAccount.value = null
  showAccountForm.value = true
}

const editAccount = async (account: any) => {
  // 如果点击编辑的是加密账号，需要先验证主密码
  if (account.username_encrypted || account.password_encrypted || account.notes_encrypted) {
    // 首先检查是否已经保存了主密码
    const savedMasterPassword = MasterPasswordSession.get()

    if (savedMasterPassword) {
      // 如果已经保存了主密码，直接使用它进行解密
      try {
        const encryptMethod = (account.encrypt_method || 'AES-256-GCM') as EncryptMethod
        const crypto = createCrypto({
          masterPassword: savedMasterPassword,
          method: encryptMethod
        })

        // 解密账号数据
        let username = ''
        let password = ''
        let notes = ''

        if (account.username_encrypted) {
          const encryptedData = JSON.parse(account.username_encrypted)
          username = crypto.decrypt(encryptedData)
        }

        if (account.password_encrypted) {
          const encryptedData = JSON.parse(account.password_encrypted)
          password = crypto.decrypt(encryptedData)
        }

        if (account.notes_encrypted) {
          const encryptedData = JSON.parse(account.notes_encrypted)
          notes = crypto.decrypt(encryptedData)
        }

        // 直接进入编辑模式
        isEditMode.value = true
        currentAccount.value = {
          ...account,
          username,
          password,
          notes
        }
        showAccountForm.value = true
        return
      } catch (error) {
        console.error('使用保存的主密码解密失败:', error)
        // 如果解密失败，清除保存的主密码，然后要求重新输入
        MasterPasswordSession.clear()
      }
    }

    // 如果没有保存的主密码或者解密失败，显示主密码输入框
    pendingAccountForView.value = account
    masterPasswordInput.value = ''
    masterPasswordError.value = ''
    showMasterPasswordModal.value = true
    // 标记这次是为了编辑
    pendingAccountForView.value._editMode = true
  } else {
    // 未加密的账号直接编辑
    isEditMode.value = true
    currentAccount.value = {
      ...account,
      username: account.username || '',
      password: account.password || '',
      notes: account.notes || ''
    }
    showAccountForm.value = true
  }
}

// 查看账号详情（需要主密码验证）
const viewAccountDetails = async (account: any) => {
  // 首先检查是否已经保存了主密码
  const savedMasterPassword = MasterPasswordSession.get()

  if (savedMasterPassword) {
    // 如果已经保存了主密码，直接使用它进行解密
    try {
      const encryptMethod = (account.encrypt_method || 'AES-256-GCM') as EncryptMethod
      const crypto = createCrypto({
        masterPassword: savedMasterPassword,
        method: encryptMethod
      })

      // 解密账号数据
      let username = ''
      let password = ''
      let notes = ''

      if (account.username_encrypted) {
        const encryptedData = JSON.parse(account.username_encrypted)
        username = crypto.decrypt(encryptedData)
      }

      if (account.password_encrypted) {
        const encryptedData = JSON.parse(account.password_encrypted)
        password = crypto.decrypt(encryptedData)
      }

      if (account.notes_encrypted) {
        const encryptedData = JSON.parse(account.notes_encrypted)
        notes = crypto.decrypt(encryptedData)
      }

      // 构建解密后的账号数据
      decryptedAccount.value = {
        ...account,
        username,
        password,
        notes
      }

      // 直接显示详情页面
      showAccountDetailModal.value = true
      showPassword.value = false
      return
    } catch (error) {
      console.error('使用保存的主密码解密失败:', error)
      // 如果解密失败，清除保存的主密码，然后要求重新输入
      MasterPasswordSession.clear()
    }
  }

  // 如果没有保存的主密码或者解密失败，显示主密码输入框
  pendingAccountForView.value = account
  masterPasswordInput.value = ''
  masterPasswordError.value = ''
  showMasterPasswordModal.value = true
}

// 验证主密码
const verifyMasterPassword = async () => {
  if (!masterPasswordInput.value) {
    masterPasswordError.value = '请输入主密码'
    return
  }

  try {
    const account = pendingAccountForView.value
    const masterPassword = masterPasswordInput.value

    // 如果勾选了"记住密码"，保存主密码到会话（30分钟内有效）
    if (rememberMasterPassword.value) {
      MasterPasswordSession.set(masterPassword)
    }

    // 获取账号的加密方法
    const encryptMethod = (account.encrypt_method || 'AES-256-GCM') as EncryptMethod
    console.log('使用加密方法解密:', encryptMethod)

    // 创建加密工具
    const crypto = createCrypto({
      masterPassword,
      method: encryptMethod
    })

    // 解密账号数据
    let username = ''
    let password = ''
    let notes = ''

    try {
      if (account.username_encrypted) {
        const encryptedData = JSON.parse(account.username_encrypted)
        username = crypto.decrypt(encryptedData)
      }

      if (account.password_encrypted) {
        const encryptedData = JSON.parse(account.password_encrypted)
        password = crypto.decrypt(encryptedData)
      }

      if (account.notes_encrypted) {
        const encryptedData = JSON.parse(account.notes_encrypted)
        notes = crypto.decrypt(encryptedData)
      }
    } catch (decryptError) {
      console.error('解密失败:', decryptError)
      masterPasswordError.value = '解密失败: ' + (decryptError as Error).message
      return
    }

    // 构建解密后的账号数据
    decryptedAccount.value = {
      ...account,
      username,
      password,
      notes
    }

    showMasterPasswordModal.value = false

    // 检查是否是编辑模式
    if (pendingAccountForView.value._editMode) {
      // 直接进入编辑模式
      isEditMode.value = true
      currentAccount.value = {
        ...decryptedAccount.value
      }
      showAccountForm.value = true
      // 清理编辑模式标记
      delete pendingAccountForView.value._editMode
    } else {
      // 显示详情页面
      showAccountDetailModal.value = true
      showPassword.value = false
    }

    masterPasswordInput.value = ''
    masterPasswordError.value = ''
    rememberMasterPassword.value = false
  } catch (error) {
    console.error('验证主密码失败:', error)
    masterPasswordError.value = '验证失败: ' + (error as Error).message
  }
}

// 切换密码显示状态
const togglePasswordVisibility = () => {
  showPassword.value = !showPassword.value
}

// 复制到剪贴板
const copyToClipboard = async (text: string) => {
  try {
    if (uni.setClipboardData) {
      uni.setClipboardData({
        data: text,
        success: () => {
          showToast('success', '已复制到剪贴板')
        },
        fail: (err) => {
          console.error('复制失败:', err)
          showToast('error', '复制失败')
        }
      })
    } else if (navigator.clipboard) {
      await navigator.clipboard.writeText(text)
      showToast('success', '已复制到剪贴板')
    } else {
      // 降级方案
      const textArea = document.createElement('textarea')
      textArea.value = text
      document.body.appendChild(textArea)
      textArea.select()
      document.execCommand('copy')
      document.body.removeChild(textArea)
      showToast('success', '已复制到剪贴板')
    }
  } catch (error) {
    console.error('复制失败:', error)
    showToast('error', '复制失败')
  }
}

// 从详情页面进入编辑模式
const editDecryptedAccount = () => {
  showAccountDetailModal.value = false
  isEditMode.value = true
  currentAccount.value = {
    ...decryptedAccount.value
  }
  showAccountForm.value = true
}

const copyPassword = async (account: any) => {
  try {
    // 获取主密码
    let masterPassword = MasterPasswordSession.get()
    if (!masterPassword) {
      masterPassword = prompt('请输入主密码以解密密码：')
      if (!masterPassword) {
        showToast('error', '需要主密码才能复制密码')
        return
      }
      MasterPasswordSession.set(masterPassword)
    }

    // 获取加密方法
    const encryptMethod = (account.encrypt_method || 'AES-256-GCM') as EncryptMethod

    // 创建解密工具
    const crypto = createCrypto({
      masterPassword,
      method: encryptMethod
    })

    // 解密密码
    let password = ''
    if (account.password_encrypted) {
      const encryptedData = JSON.parse(account.password_encrypted)
      password = crypto.decrypt(encryptedData)
    } else {
      showToast('error', '该账号没有设置密码')
      return
    }

    // 使用现代浏览器的Clipboard API
    if (navigator.clipboard) {
      await navigator.clipboard.writeText(password)
      showToast('success', '密码已复制到剪贴板')
    } else {
      // 降级方案
      const textArea = document.createElement('textarea')
      textArea.value = password
      document.body.appendChild(textArea)
      textArea.select()
      document.execCommand('copy')
      document.body.removeChild(textArea)
      showToast('success', '密码已复制到剪贴板')
    }
  } catch (error) {
    console.error('复制密码失败:', error)
    showToast('error', '复制密码失败，请重试')
  }
}

const deleteAccount = async (account: any) => {
  if (!confirm(`确定要删除账号 ${account.name} 吗？`)) {
    return
  }

  try {
    const response = await fetch(`/api/accounts/${account.id}`, {
      method: 'DELETE',
      headers: getAuthHeaders()
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        showToast('success', '删除成功')
        loadAccounts()
        loadStats()
      } else {
        showToast('error', '删除失败: ' + result.message)
      }
    }
  } catch (error) {
    console.error('删除账号失败:', error)
    showToast('error', '删除失败，请重试')
  }
}

const refreshAccounts = () => {
  loadAccounts()
  loadStats()
  showToast('success', '数据已刷新')
}

// 表单操作
const closeAccountForm = () => {
  showAccountForm.value = false
  currentAccount.value = null
}

const saveAccount = async (accountData: any) => {
  try {
    console.log('保存账号数据:', accountData)

    // 获取主密码
    let masterPassword = MasterPasswordSession.get()
    if (!masterPassword) {
      masterPassword = prompt('请输入主密码以加密账号信息：')
      if (!masterPassword) {
        showToast('error', '必须输入主密码才能保存账号')
        return
      }
      // 保存主密码到会话
      MasterPasswordSession.set(masterPassword)
    }

    // 创建加密工具
    const encryptMethod = accountData.encrypt_method || 'AES-256-GCM'
    const crypto = createCrypto({
      masterPassword,
      method: encryptMethod as EncryptMethod
    })

    // 加密敏感数据
    const usernameEncryptResult = crypto.encrypt(accountData.username)
    const passwordEncryptResult = crypto.encrypt(accountData.password)
    const notesEncryptResult = accountData.notes ? crypto.encrypt(accountData.notes) : null

    const encryptedData = {
      ...accountData,
      username: JSON.stringify(usernameEncryptResult),
      password: JSON.stringify(passwordEncryptResult),
      notes: notesEncryptResult ? JSON.stringify(notesEncryptResult) : ''
    }

    console.log('加密后的数据:', encryptedData)

    const url = isEditMode.value ? `/api/accounts/${currentAccount.value.id}` : '/api/accounts'
    const method = isEditMode.value ? 'PUT' : 'POST'

    const response = await fetch(url, {
      method,
      headers: getAuthHeaders(),
      body: JSON.stringify(encryptedData)
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        showToast('success', isEditMode.value ? '更新成功' : '添加成功')
        closeAccountForm()
        loadAccounts()
        loadStats()
      } else {
        showToast('error', '保存失败: ' + result.message)
      }
    }
  } catch (error) {
    console.error('保存账号失败:', error)
    showToast('error', '保存失败: ' + (error as Error).message)
  }
}

// 分类操作
const addCategory = () => {
  const name = prompt('请输入分类名称:')
  if (!name) return

  const description = prompt('请输入分类描述(可选):') || ''

  saveCategoryData({ name, description })
}

const editCategory = (category: any) => {
  const name = prompt('请输入新的分类名称:', category.name)
  if (!name) return

  const description = prompt('请输入分类描述:', category.description || '') || ''

  saveCategoryData({ id: category.id, name, description })
}

const deleteCategory = async (category: any) => {
  if (!confirm(`确定要删除分类 ${category.name} 吗？`)) {
    return
  }

  try {
    const response = await fetch(`/api/categories/${category.id}`, {
      method: 'DELETE',
      headers: getAuthHeaders()
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        showToast('success', '删除成功')
        loadCategories()
      } else {
        showToast('error', '删除失败: ' + result.message)
      }
    }
  } catch (error) {
    console.error('删除分类失败:', error)
    showToast('error', '删除失败，请重试')
  }
}

const saveCategoryData = async (categoryData: any) => {
  try {
    const url = categoryData.id ? `/api/categories/${categoryData.id}` : '/api/categories'
    const method = categoryData.id ? 'PUT' : 'POST'

    const response = await fetch(url, {
      method,
      headers: getAuthHeaders(),
      body: JSON.stringify(categoryData)
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        showToast('success', categoryData.id ? '更新成功' : '添加成功')
        loadCategories()
      } else {
        showToast('error', '保存失败: ' + result.message)
      }
    }
  } catch (error) {
    console.error('保存分类失败:', error)
    showToast('error', '保存失败，请重试')
  }
}

// 安全设置方法 - 主密码修改向导
const passwordChangeStep = ref(1)
const isReencrypting = ref(false)
const reencryptProgress = ref(0)
const reencryptedCount = ref(0)
const estimatedTime = computed(() => {
  const totalAccounts = accounts.value.length
  const secondsPerAccount = 0.1
  return Math.ceil(totalAccounts * secondsPerAccount)
})

const changeMasterPassword = async () => {
  // 步骤1: 验证密码输入
  if (passwordChangeStep.value === 1) {
    if (passwordForm.value.newPassword !== passwordForm.value.confirmPassword) {
      showToast('error', '两次输入的密码不一致')
      return
    }

    if (passwordForm.value.newPassword.length < 8) {
      showToast('error', '新密码长度至少8位')
      return
    }

    // 进入步骤2: 确认信息
    passwordChangeStep.value = 2
    return
  }

  // 步骤2: 确认并开始处理
  if (passwordChangeStep.value === 2) {
    if (!confirm('确定要修改主密码吗？这将重新加密所有账号数据，需要一些时间。')) {
      return
    }

    passwordChangeStep.value = 3
    isReencrypting.value = true
    reencryptProgress.value = 0
    reencryptedCount.value = 0

    try {
      const response = await fetch('/api/user/change-master-password', {
        method: 'PUT',
        headers: getAuthHeaders(),
        body: JSON.stringify({
          current_password: passwordForm.value.currentPassword,
          new_password: passwordForm.value.newPassword,
          hint: passwordForm.value.hint
        })
      })

      // 模拟进度更新
      const totalAccounts = accounts.value.length
      const progressInterval = setInterval(() => {
        if (reencryptedCount.value < totalAccounts) {
          reencryptedCount.value += Math.ceil(totalAccounts / 20)
          if (reencryptedCount.value > totalAccounts) {
            reencryptedCount.value = totalAccounts
          }
          reencryptProgress.value = Math.floor((reencryptedCount.value / totalAccounts) * 100)
        } else {
          clearInterval(progressInterval)
        }
      }, 100)

      if (response.ok) {
        const result = await response.json()
        clearInterval(progressInterval)

        if (result.code === 200) {
          reencryptProgress.value = 100
          reencryptedCount.value = totalAccounts

          setTimeout(() => {
            showToast('success', '主密码修改成功！所有数据已重新加密')
            showChangePasswordModal.value = false
            passwordForm.value = {
              currentPassword: '',
              newPassword: '',
              confirmPassword: '',
              hint: ''
            }
            passwordChangeStep.value = 1
            isReencrypting.value = false
          }, 500)
        } else {
          showToast('error', result.message)
          passwordChangeStep.value = 1
          isReencrypting.value = false
        }
      }
    } catch (error) {
      console.error('修改主密码失败:', error)
      showToast('error', '修改失败，请重试')
      passwordChangeStep.value = 1
      isReencrypting.value = false
    }
  }
}

const cancelPasswordChange = () => {
  passwordChangeStep.value = 1
  passwordForm.value = {
    currentPassword: '',
    newPassword: '',
    confirmPassword: '',
    hint: ''
  }
}

const changeLoginPassword = async () => {
  if (loginPasswordForm.value.newPassword !== loginPasswordForm.value.confirmPassword) {
    showToast('error', '两次输入的密码不一致')
    return
  }

  try {
    const response = await fetch('/api/user/password', {
      method: 'PUT',
      headers: getAuthHeaders(),
      body: JSON.stringify({
        current_password: loginPasswordForm.value.currentPassword,
        new_password: loginPasswordForm.value.newPassword
      })
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        showToast('success', '登录密码修改成功')
        showChangeLoginPasswordModal.value = false
        loginPasswordForm.value = {
          currentPassword: '',
          newPassword: '',
          confirmPassword: ''
        }
      } else {
        showToast('error', result.message)
      }
    }
  } catch (error) {
    console.error('修改登录密码失败:', error)
    showToast('error', '修改失败，请重试')
  }
}

const changeEncryptMethod = async () => {
  if (selectedEncryptMethod.value === securityInfo.value.encryptMethod) {
    showToast('warning', '已经是当前加密方式')
    return
  }

  if (!confirm('更改加密方式需要重新加密所有数据，此过程不可逆，确定继续吗？')) {
    return
  }

  try {
    const response = await fetch('/api/user/encrypt-method', {
      method: 'PUT',
      headers: getAuthHeaders(),
      body: JSON.stringify({
        encrypt_method: selectedEncryptMethod.value
      })
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        showToast('success', '加密方式修改成功')
        securityInfo.value.encryptMethod = selectedEncryptMethod.value
      } else {
        showToast('error', result.message)
      }
    }
  } catch (error) {
    console.error('修改加密方式失败:', error)
    showToast('error', '修改失败，请重试')
  }
}

const loadUserDevices = async () => {
  try {
    const response = await fetch('/api/user/devices', {
      headers: getAuthHeaders()
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        userDevices.value = result.data
      }
    }
  } catch (error) {
    console.error('加载设备列表失败:', error)
  }
}

const removeDevice = async (deviceId: number) => {
  if (!confirm('确定要移除此设备吗？')) {
    return
  }

  try {
    const response = await fetch(`/api/user/devices`, {
      method: 'DELETE',
      headers: getAuthHeaders(),
      body: JSON.stringify({ device_id: deviceId })
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        showToast('success', '设备移除成功')
        loadUserDevices()
      } else {
        showToast('error', result.message)
      }
    }
  } catch (error) {
    console.error('移除设备失败:', error)
    showToast('error', '移除失败，请重试')
  }
}

const enableBiometric = async () => {
  try {
    // 检查设备是否支持生物识别
    if (window.PublicKeyCredential) {
      const result = await navigator.credentials.create({
        publicKey: {
          challenge: new Uint8Array(32),
          rp: { name: '账号密码管理器', id: window.location.hostname },
          user: {
            id: new TextEncoder().encode(userInfo.value.id.toString()),
            name: userInfo.value.username,
            displayName: userInfo.value.nickname
          },
          pubKeyCredParams: [{ alg: -7, type: 'public-key' }],
          authenticatorSelection: {
            authenticatorAttachment: 'platform',
            userVerification: 'required'
          }
        }
      })

      if (result) {
        securityInfo.value.biometricEnabled = true
        showToast('success', '生物识别启用成功')
      }
    } else {
      showToast('error', '当前设备不支持生物识别')
    }
  } catch (error) {
    console.error('启用生物识别失败:', error)
    showToast('error', '启用失败，请重试')
  }
}

const disableBiometric = () => {
  if (confirm('确定要禁用生物识别吗？')) {
    securityInfo.value.biometricEnabled = false
    localStorage.removeItem('biometric_enabled')
    showToast('success', '生物识别已禁用')
  }
}

const loadSecurityLogs = async () => {
  try {
    const response = await fetch('/api/user/logs?limit=10', {
      headers: getAuthHeaders()
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        securityLogs.value = result.data
      }
    }
  } catch (error) {
    console.error('加载安全日志失败:', error)
  }
}

const loadEncryptMethods = async () => {
  try {
    const response = await fetch('/api/system/encrypt-methods')

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        encryptMethods.value = result.data
      }
    }
  } catch (error) {
    console.error('加载加密方式失败:', error)
  }
}

// 个人资料方法
const updateProfile = async () => {
  try {
    const response = await fetch('/api/user/info', {
      method: 'PUT',
      headers: getAuthHeaders(),
      body: JSON.stringify({
        nickname: profileForm.value.nickname,
        email: profileForm.value.email,
        phone: profileForm.value.phone
      })
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        userInfo.value = { ...userInfo.value, ...profileForm.value }
        showToast('success', '个人资料更新成功')
      } else {
        showToast('error', result.message)
      }
    }
  } catch (error) {
    console.error('更新个人资料失败:', error)
    showToast('error', '更新失败，请重试')
  }
}

const resetProfileForm = () => {
  profileForm.value = {
    nickname: userInfo.value.nickname,
    email: userInfo.value.email,
    phone: userInfo.value.phone
  }
}

const changeAvatar = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = 'image/*'
  input.onchange = async (e) => {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (file) {
      const formData = new FormData()
      formData.append('avatar', file)

      try {
        const response = await fetch('/api/user/avatar', {
          method: 'POST',
          headers: {
            'Authorization': `Bearer ${localStorage.getItem('token')}`
          },
          body: formData
        })

        if (response.ok) {
          const result = await response.json()
          if (result.code === 200) {
            userInfo.value.avatar = result.data.avatar
            showToast('success', '头像更新成功')
          }
        }
      } catch (error) {
        console.error('上传头像失败:', error)
        showToast('error', '头像上传失败')
      }
    }
  }
  input.click()
}

const sendEmailVerification = async () => {
  try {
    const response = await fetch('/api/user/verify-email', {
      method: 'POST',
      headers: getAuthHeaders()
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        showToast('success', '验证邮件已发送')
      } else {
        showToast('error', result.message)
      }
    }
  } catch (error) {
    console.error('发送验证邮件失败:', error)
    showToast('error', '发送失败，请重试')
  }
}

const sendPhoneVerification = async () => {
  try {
    const response = await fetch('/api/user/verify-phone', {
      method: 'POST',
      headers: getAuthHeaders()
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        showToast('success', '验证短信已发送')
      } else {
        showToast('error', result.message)
      }
    }
  } catch (error) {
    console.error('发送验证短信失败:', error)
    showToast('error', '发送失败，请重试')
  }
}

const bindAccount = async (platform: string) => {
  try {
    // 步骤1: 获取授权URL
    const response = await fetch('/api/auth/bind', {
      method: 'POST',
      headers: getAuthHeaders(),
      body: JSON.stringify({
        platform,
        redirect_uri: window.location.origin + '/oauth-callback'
      })
    })

    const result = await response.json()

    if (result.code === 200 && result.data.auth_url) {
      // 步骤2: 打开授权窗口
      const authWindow = window.open(
        result.data.auth_url,
        `${platform}_bind`,
        'width=600,height=700,left=200,top=100'
      )

      if (!authWindow) {
        showToast('error', '请允许弹出窗口以完成绑定')
        return
      }

      // 步骤3: 监听绑定回调
      const checkBindStatus = setInterval(async () => {
        try {
          if (authWindow.closed) {
            clearInterval(checkBindStatus)
            // 刷新绑定状态
            loadBindings()
            return
          }

          try {
            const authUrl = authWindow.location.href
            if (authUrl.includes('oauth-callback')) {
              const urlParams = new URLSearchParams(authWindow.location.search)
              const code = urlParams.get('code')

              if (code) {
                authWindow.close()
                clearInterval(checkBindStatus)

                // 步骤4: 完成绑定
                const bindResponse = await fetch('/api/auth/bind/callback', {
                  method: 'POST',
                  headers: getAuthHeaders(),
                  body: JSON.stringify({ platform, code })
                })

                const bindResult = await bindResponse.json()

                if (bindResult.code === 200) {
                  showToast('success', `${getPlatformName(platform)}绑定成功`)
                  loadBindings()
                } else {
                  showToast('error', `绑定失败: ${bindResult.message}`)
                }
              }
            }
          } catch (e) {
            // 跨域忽略
          }
        } catch (error) {
          console.error('检查绑定状态失败:', error)
        }
      }, 1000)

      // 5分钟超时
      setTimeout(() => {
        clearInterval(checkBindStatus)
        if (!authWindow.closed) {
          authWindow.close()
        }
      }, 300000)

    } else {
      showToast('error', `获取授权失败: ${result.message}`)
    }

  } catch (error) {
    console.error('绑定失败:', error)
    showToast('error', '绑定失败,请重试')
  }
}

const unbindAccount = async (platform: string) => {
  if (!confirm(`确定要解绑${getPlatformName(platform)}账号吗？解绑后将无法使用该平台登录。`)) {
    return
  }

  try {
    const response = await fetch('/api/auth/unbind', {
      method: 'DELETE',
      headers: getAuthHeaders(),
      body: JSON.stringify({ platform })
    })

    const result = await response.json()

    if (result.code === 200) {
      showToast('success', `${getPlatformName(platform)}解绑成功`)
      loadBindings()
    } else {
      showToast('error', `解绑失败: ${result.message}`)
    }

  } catch (error) {
    console.error('解绑失败:', error)
    showToast('error', '解绑失败,请重试')
  }
}

// 加载绑定列表
const loadBindings = async () => {
  try {
    const response = await fetch('/api/auth/bindings', {
      headers: getAuthHeaders()
    })

    const result = await response.json()

    if (result.code === 200) {
      // 更新绑定状态
      const bindings = result.data
      // 可以在这里更新UI显示绑定状态
    }

  } catch (error) {
    console.error('加载绑定列表失败:', error)
  }
}

// 导入导出相关状态
const showImportExportModal = ref(false)
const exportFormat = ref<'json' | 'csv'>('json')
const importFile = ref<File | null>(null)
const importProgress = ref(0)
const isImporting = ref(false)
const isExporting = ref(false)
const backupList = ref<any[]>([])
const showBackupModal = ref(false)

// 通知相关
const notifications = ref<any[]>([])
const notificationStats = ref({
  total: 0,
  high_priority: 0,
  expiring: 0,
  expired: 0
})
const notificationFilter = ref('all')
const filteredNotifications = computed(() => {
  if (notificationFilter.value === 'all') {
    return notifications.value
  } else if (notificationFilter.value === 'high') {
    return notifications.value.filter(n => n.priority >= 4)
  } else if (notificationFilter.value === 'expiring') {
    return notifications.value.filter(n => n.type === 'password_expiring')
  } else if (notificationFilter.value === 'expired') {
    return notifications.value.filter(n => n.type === 'password_expired')
  }
  return notifications.value
})

// 加载通知
const loadNotifications = async () => {
  try {
    const response = await fetch('/api/notifications', {
      headers: getAuthHeaders()
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        notifications.value = result.data
      }
    }
  } catch (error) {
    console.error('加载通知失败:', error)
  }

  // 加载通知统计
  try {
    const response = await fetch('/api/notifications/stats', {
      headers: getAuthHeaders()
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        notificationStats.value = result.data
      }
    }
  } catch (error) {
    console.error('加载通知统计失败:', error)
  }
}

// 筛选通知
const filterNotifications = (filter: string) => {
  notificationFilter.value = filter
}

// 获取通知图标
const getNotificationIcon = (type: string) => {
  const icons: Record<string, string> = {
    password_expiring: '⏰',
    password_expired: '⚠️',
    account_unused: '😴',
    security_alert: '🔔',
    system: '💬'
  }
  return icons[type] || '📬'
}

// 获取优先级文本
const getPriorityText = (priority: number) => {
  if (priority >= 5) return '紧急'
  if (priority >= 4) return '高'
  if (priority >= 3) return '中'
  if (priority >= 2) return '低'
  return '一般'
}

// 跳转到账号
const goToAccount = (accountId: number) => {
  setActiveTab('accounts')
  // 可以进一步实现高亮显示或滚动到对应账号
}

// 统计图表数据
const categoryStats = ref<any[]>([])
const usageTrend = ref<any[]>([])
const healthScore = ref(85)
const healthDetails = ref({
  strong_passwords: 0,
  weak_passwords: 0,
  active_accounts: 0
})

// 加载统计数据
const loadStatistics = async () => {
  try {
    // 分类统计
    const response1 = await fetch('/api/statistics/category-usage', {
      headers: getAuthHeaders()
    })
    if (response1.ok) {
      const result = await response1.json()
      if (result.code === 200) {
        categoryStats.value = result.data
      }
    }

    // 使用趋势
    const response2 = await fetch('/api/statistics/trend?days=7', {
      headers: getAuthHeaders()
    })
    if (response2.ok) {
      const result = await response2.json()
      if (result.code === 200) {
        usageTrend.value = result.data
      }
    }

    // 健康评分
    const response3 = await fetch('/api/statistics/health-score', {
      headers: getAuthHeaders()
    })
    if (response3.ok) {
      const result = await response3.json()
      if (result.code === 200) {
        healthScore.value = result.data.score
        healthDetails.value = result.data.details
      }
    }
  } catch (error) {
    console.error('加载统计数据失败:', error)
  }
}

// 图表颜色
const chartColors = [
  '#1890ff', '#52c41a', '#faad14', '#f5222d', '#722ed1',
  '#13c2c2', '#eb2f96', '#fa8c16', '#2f54eb', '#a0d911'
]

const getChartColor = (index: number) => {
  return chartColors[index % chartColors.length]
}

// 计算百分比
const getPercentage = (value: number, total: number) => {
  if (total === 0) return 0
  return Math.round((value / total) * 100)
}

// 饼图数据
const pieChartSegments = computed(() => {
  const total = stats.value.totalAccounts || 1
  let offset = 0
  const circumference = 502.4 // 2 * PI * 80

  return categoryStats.value.map((item, index) => {
    const percentage = item.count / total
    const dashArray = circumference * percentage
    const segment = {
      color: getChartColor(index),
      dashArray,
      dashOffset: -offset
    }
    offset += dashArray
    return segment
  })
})

// 柱状图高度
const getBarHeight = (count: number) => {
  if (usageTrend.value.length === 0) return 0
  const maxCount = Math.max(...usageTrend.value.map(d => d.count), 1)
  return Math.max((count / maxCount) * 100, 5) // 最小5%高度
}

// 柱状图颜色渐变
const getGradientColor = (count: number) => {
  const maxCount = Math.max(...usageTrend.value.map(d => d.count), 1)
  const ratio = count / maxCount
  if (ratio > 0.7) return 'linear-gradient(180deg, #52c41a, #73d13d)'
  if (ratio > 0.4) return 'linear-gradient(180deg, #1890ff, #40a9ff)'
  return 'linear-gradient(180deg, #faad14, #ffc53d)'
}

// 格式化日期标签
const formatDayLabel = (date: string) => {
  const d = new Date(date)
  const today = new Date()
  const yesterday = new Date(today)
  yesterday.setDate(yesterday.getDate() - 1)

  if (d.toDateString() === today.toDateString()) {
    return '今天'
  } else if (d.toDateString() === yesterday.toDateString()) {
    return '昨天'
  } else {
    return `${d.getMonth() + 1}/${d.getDate()}`
  }
}

// 健康度颜色
const getHealthColor = (score: number) => {
  if (score >= 80) return '#52c41a'
  if (score >= 60) return '#1890ff'
  if (score >= 40) return '#faad14'
  return '#f5222d'
}

// 健康度标签
const getHealthLabel = (score: number) => {
  if (score >= 90) return '优秀'
  if (score >= 80) return '良好'
  if (score >= 60) return '一般'
  if (score >= 40) return '较差'
  return '危险'
}

// 导出数据
const exportData = async () => {
  showImportExportModal.value = true
}

// 执行导出
const performExport = async () => {
  try {
    isExporting.value = true

    if (exportFormat.value === 'json') {
      const response = await fetch('/api/import/export-json', {
        headers: getAuthHeaders()
      })

      if (response.ok) {
        const result = await response.json()
        if (result.code === 200) {
          // 使用工具函数导出
          const { exportToJsonFile } = await import('@/utils/import-export')
          exportToJsonFile(result.data, `账号数据_${Date.now()}.json`)
          showToast('success', '数据导出成功')
          showImportExportModal.value = false
        } else {
          showToast('error', '导出失败: ' + result.message)
        }
      }
    } else {
      const response = await fetch('/api/import/export-csv', {
        headers: getAuthHeaders()
      })

      if (response.ok) {
        const result = await response.json()
        if (result.code === 200) {
          const { exportToCsvFile } = await import('@/utils/import-export')
          exportToCsvFile(result.data, `账号数据_${Date.now()}.csv`)
          showToast('success', 'CSV导出成功')
          showImportExportModal.value = false
        } else {
          showToast('error', '导出失败: ' + result.message)
        }
      }
    }
  } catch (error) {
    console.error('导出失败:', error)
    showToast('error', '导出失败,请重试')
  } finally {
    isExporting.value = false
  }
}

// 选择导入文件
const importData = () => {
  const input = document.createElement('input')
  input.type = 'file'
  input.accept = '.json,.csv'
  input.onchange = async (e) => {
    const file = (e.target as HTMLInputElement).files?.[0]
    if (file) {
      await handleImportFile(file)
    }
  }
  input.click()
}

// 处理导入文件
const handleImportFile = async (file: File) => {
  try {
    isImporting.value = true
    importProgress.value = 0

    const fileExt = file.name.split('.').pop()?.toLowerCase()

    if (fileExt === 'json') {
      const { readJsonFile } = await import('@/utils/import-export')
      const data = await readJsonFile(file)

      importProgress.value = 50

      const response = await fetch('/api/import/import-json', {
        method: 'POST',
        headers: getAuthHeaders(),
        body: JSON.stringify({
          data,
          skip_duplicates: true,
          update_existing: false
        })
      })

      if (response.ok) {
        const result = await response.json()
        if (result.code === 200) {
          importProgress.value = 100
          showToast('success', `成功导入 ${result.data.imported} 条记录${result.data.skipped ? `, 跳过 ${result.data.skipped} 条重复` : ''}`)
          loadAccounts()
          loadStats()
        } else {
          showToast('error', '导入失败: ' + result.message)
        }
      }
    } else if (fileExt === 'csv') {
      const { readCsvFile } = await import('@/utils/import-export')
      const data = await readCsvFile(file)

      importProgress.value = 50

      const response = await fetch('/api/import/import-csv', {
        method: 'POST',
        headers: getAuthHeaders(),
        body: JSON.stringify({
          data,
          skip_duplicates: true
        })
      })

      if (response.ok) {
        const result = await response.json()
        if (result.code === 200) {
          importProgress.value = 100
          showToast('success', `成功导入 ${result.data.imported} 条记录`)
          loadAccounts()
          loadStats()
        } else {
          showToast('error', '导入失败: ' + result.message)
        }
      }
    } else {
      showToast('error', '不支持的文件格式')
    }
  } catch (error) {
    console.error('导入失败:', error)
    showToast('error', '导入失败: ' + (error as Error).message)
  } finally {
    isImporting.value = false
    setTimeout(() => {
      importProgress.value = 0
    }, 2000)
  }
}

// 创建备份
const createBackupNow = async () => {
  try {
    const response = await fetch('/api/import/create-backup', {
      method: 'POST',
      headers: getAuthHeaders()
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        showToast('success', '备份创建成功')
        if (showBackupModal.value) {
          loadBackupList()
        }
      } else {
        showToast('error', '备份失败: ' + result.message)
      }
    }
  } catch (error) {
    console.error('创建备份失败:', error)
    showToast('error', '备份失败,请重试')
  }
}

// 管理备份
const manageBackups = async () => {
  showBackupModal.value = true
  await loadBackupList()
}

// 加载备份列表
const loadBackupList = async () => {
  try {
    const response = await fetch('/api/import/list-backups', {
      headers: getAuthHeaders()
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        backupList.value = result.data
      }
    }
  } catch (error) {
    console.error('加载备份列表失败:', error)
  }
}

// 恢复备份
const restoreBackupFile = async (filename: string) => {
  if (!confirm(`确定要恢复备份 ${filename} 吗?这将覆盖当前数据!`)) {
    return
  }

  try {
    const response = await fetch('/api/import/restore-backup', {
      method: 'POST',
      headers: getAuthHeaders(),
      body: JSON.stringify({ filename })
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        showToast('success', '备份恢复成功')
        showBackupModal.value = false
        loadAccounts()
        loadStats()
      } else {
        showToast('error', '恢复失败: ' + result.message)
      }
    }
  } catch (error) {
    console.error('恢复备份失败:', error)
    showToast('error', '恢复失败,请重试')
  }
}

// 删除备份
const deleteBackupFile = async (filename: string) => {
  if (!confirm(`确定要删除备份 ${filename} 吗?`)) {
    return
  }

  try {
    const response = await fetch('/api/import/delete-backup', {
      method: 'DELETE',
      headers: getAuthHeaders(),
      body: JSON.stringify({ filename })
    })

    if (response.ok) {
      const result = await response.json()
      if (result.code === 200) {
        showToast('success', '备份删除成功')
        loadBackupList()
      } else {
        showToast('error', '删除失败: ' + result.message)
      }
    }
  } catch (error) {
    console.error('删除备份失败:', error)
    showToast('error', '删除失败,请重试')
  }
}

// 格式化文件大小
const formatFileSize = (bytes: number): string => {
  if (bytes === 0) return '0 B'
  const k = 1024
  const sizes = ['B', 'KB', 'MB', 'GB']
  const i = Math.floor(Math.log(bytes) / Math.log(k))
  return Math.round(bytes / Math.pow(k, i) * 100) / 100 + ' ' + sizes[i]
}

const clearAllData = async () => {
  // 第一次确认
  if (!confirm('⚠️ 警告：确定要清空所有账号数据吗？\n\n此操作将删除：\n• 所有账号信息\n• 所有分类信息\n• 所有操作日志\n\n此操作不可恢复！')) {
    return
  }

  // 第二次确认 - 要求输入"DELETE"
  const confirmText = prompt('请输入 DELETE 确认删除所有数据：')
  if (confirmText !== 'DELETE') {
    if (confirmText !== null) {
      showToast('error', '输入错误,操作已取消')
    }
    return
  }

  // 第三次确认 - 要求输入主密码
  const masterPassword = prompt('最后确认：请输入主密码')
  if (!masterPassword) {
    return
  }

  try {
    const response = await fetch('/api/accounts/batch-delete', {
      method: 'POST',
      headers: getAuthHeaders(),
      body: JSON.stringify({
        account_ids: accounts.value.map(a => a.id),
        master_password: masterPassword
      })
    })

    const result = await response.json()

    if (result.code === 200) {
      showToast('success', '所有数据已清空')
      // 刷新数据
      accounts.value = []
      loadStats()
      loadAccounts()
      loadCategories()
    } else {
      showToast('error', '清空失败: ' + result.message)
    }

  } catch (error) {
    console.error('清空数据失败:', error)
    showToast('error', '清空失败,请重试')
  }
}

const deleteUserAccount = async () => {
  // 第一次确认
  if (!confirm('🚨 严重警告：确定要注销账户吗？\n\n此操作将永久删除：\n• 您的用户账户\n• 所有账号数据\n• 所有分类和设置\n• 所有操作记录\n\n此操作无法撤销！')) {
    return
  }

  // 第二次确认 - 要求输入用户名
  const username = userInfo.value.username
  const confirmUsername = prompt(`请输入您的用户名 "${username}" 以确认注销：`)
  if (confirmUsername !== username) {
    if (confirmUsername !== null) {
      showToast('error', '用户名不匹配,操作已取消')
    }
    return
  }

  // 第三次确认 - 要求输入主密码
  const masterPassword = prompt('最后确认：请输入主密码')
  if (!masterPassword) {
    return
  }

  // 倒计时10秒
  let countdown = 10
  const countdownInterval = setInterval(() => {
    countdown--
    if (countdown > 0) {
      showToast('warning', `账户将在 ${countdown} 秒后注销...`)
    } else {
      clearInterval(countdownInterval)
    }
  }, 1000)

  // 用户可以在10秒内取消
  const cancelCountdown = confirm('账户将在10秒后注销,点击"取消"可以中止操作')
  if (!cancelCountdown) {
    clearInterval(countdownInterval)
    showToast('info', '注销已取消')
    return
  }

  // 等待10秒
  await new Promise(resolve => setTimeout(resolve, 10000))

  try {
    const response = await fetch('/api/user/account', {
      method: 'DELETE',
      headers: getAuthHeaders(),
      body: JSON.stringify({
        master_password: masterPassword
      })
    })

    const result = await response.json()

    if (result.code === 200) {
      showToast('success', '账户已注销')
      // 清空本地数据
      localStorage.clear()
      // 跳转到登录页
      setTimeout(() => {
        router.push('/login')
      }, 2000)
    } else {
      showToast('error', '注销失败: ' + result.message)
    }

  } catch (error) {
    console.error('注销账户失败:', error)
    showToast('error', '注销失败,请重试')
  }
}

// 工具函数
const formatTime = (timeStr: string) => {
  if (!timeStr) return '从未'
  const date = new Date(timeStr)
  return date.toLocaleString('zh-CN')
}

const getDeviceIcon = (platform: string) => {
  const icons = {
    h5: '🌐',
    wechat: '💬',
    alipay: '💳',
    douyin: '🎵',
    ios: '📱',
    android: '🤖'
  }
  return icons[platform] || '💻'
}

const getLogIcon = (action: string) => {
  const icons = {
    login: '🔑',
    logout: '🚪',
    'create-account': '➕',
    'update-account': '✏️',
    'delete-account': '🗑️',
    'change-password': '🔐'
  }
  return icons[action] || '📝'
}

const getPlatformIcon = (platform: string) => {
  const icons = {
    wechat: '💬',
    alipay: '💳',
    douyin: '🎵'
  }
  return icons[platform] || '🔗'
}

const getPlatformName = (platform: string) => {
  const names = {
    wechat: '微信',
    alipay: '支付宝',
    douyin: '抖音'
  }
  return names[platform] || platform
}

const logout = () => {
  if (confirm('确定要退出登录吗？')) {
    localStorage.removeItem('userInfo')
    localStorage.removeItem('token')
    router.push('/login')
  }
}

// 工具函数
const formatDate = (dateStr: string) => {
  const date = new Date(dateStr)
  return date.toLocaleDateString('zh-CN')
}
</script>

<style scoped>
.dashboard {
  min-height: 100vh;
  background: var(--bg-secondary);
}

.dashboard-header {
  background: var(--header-bg);
  border-bottom: 1px solid var(--header-border);
  padding: 0 20px;
  position: sticky;
  top: 0;
  z-index: 100;
}

.header-content {
  display: flex;
  justify-content: space-between;
  align-items: center;
  height: 64px;
  max-width: 1200px;
  margin: 0 auto;
}

.logo h1 {
  font-size: 20px;
  margin: 0;
  color: var(--primary-color);
}

.user-info {
  display: flex;
  align-items: center;
  gap: 16px;
}

.username {
  font-weight: 500;
  color: var(--header-text);
}

.lang-toggle-btn,
.theme-toggle-btn {
  padding: 6px 12px;
  background: var(--bg-tertiary);
  color: var(--text-primary);
  border: 1px solid var(--border-color);
  border-radius: 4px;
  cursor: pointer;
  font-size: 18px;
  transition: all 0.2s;
  display: flex;
  align-items: center;
  justify-content: center;
}

.lang-toggle-btn:hover,
.theme-toggle-btn:hover {
  background: var(--bg-secondary);
  border-color: var(--primary-color);
  transform: scale(1.05);
}

.logout-btn {
  padding: 6px 12px;
  background: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.logout-btn:hover {
  background: #ff7875;
}

.dashboard-main {
  display: flex;
  max-width: 1200px;
  margin: 0 auto;
  padding: 20px;
  gap: 20px;
}

.sidebar {
  width: 240px;
  background: white;
  border-radius: 8px;
  padding: 20px 0;
  height: fit-content;
  position: sticky;
  top: 84px;
}

.nav-menu {
  display: flex;
  flex-direction: column;
}

.menu-item {
  padding: 12px 20px;
  cursor: pointer;
  transition: all 0.2s;
  border-left: 3px solid transparent;
}

.menu-item:hover {
  background: #f0f0f0;
}

.menu-item.active {
  background: #e6f7ff;
  border-left-color: #1890ff;
  color: #1890ff;
  font-weight: 500;
}

.menu-badge {
  background: #ff4d4f;
  color: white;
  font-size: 11px;
  padding: 2px 6px;
  border-radius: 10px;
  margin-left: 8px;
  font-weight: 600;
}

.content {
  flex: 1;
  background: white;
  border-radius: 8px;
  padding: 24px;
}

.content-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 24px;
}

.content-header h2 {
  margin: 0;
  color: #333;
}

.actions {
  display: flex;
  gap: 8px;
}

.btn-primary {
  padding: 8px 16px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.btn-primary:hover {
  background: #40a9ff;
}

.btn-secondary {
  padding: 8px 16px;
  background: #f0f0f0;
  color: #333;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
}

.btn-secondary:hover {
  background: #e6e6e6;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
  margin-bottom: 32px;
}

.stat-card {
  background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
  color: white;
  padding: 20px;
  border-radius: 8px;
  display: flex;
  align-items: center;
  gap: 16px;
}

.stat-icon {
  font-size: 32px;
}

.stat-number {
  font-size: 24px;
  font-weight: 600;
  margin-bottom: 4px;
}

.stat-label {
  font-size: 14px;
  opacity: 0.9;
}

.recent-section h3 {
  margin-bottom: 16px;
  color: #333;
}

.recent-accounts {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.account-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.account-icon {
  font-size: 20px;
}

.account-info {
  flex: 1;
}

.account-name {
  font-weight: 500;
  color: #333;
}

.account-category {
  font-size: 12px;
  color: #666;
}

.account-date {
  font-size: 12px;
  color: #999;
}

.search-bar {
  display: flex;
  gap: 12px;
  margin-bottom: 20px;
}

.search-input {
  flex: 1;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
}

.category-filter {
  width: 150px;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
}

.accounts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fill, minmax(300px, 1fr));
  gap: 16px;
}

.account-card {
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  overflow: hidden;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  background: #fafafa;
  border-bottom: 1px solid #e8e8e8;
}

.account-title {
  font-weight: 500;
  color: #333;
}

.account-actions {
  display: flex;
  gap: 4px;
}

.action-btn {
  padding: 4px 8px;
  border: none;
  background: transparent;
  cursor: pointer;
  border-radius: 4px;
  font-size: 14px;
}

.action-btn:hover {
  background: #e6e6e6;
}

.action-btn.delete:hover {
  background: #fff2f0;
  color: #ff4d4f;
}

.card-content {
  padding: 16px;
}

.account-detail {
  display: flex;
  justify-content: space-between;
  margin-bottom: 8px;
}

.label {
  color: #666;
  font-size: 14px;
}

.value {
  color: #333;
  font-size: 14px;
  font-weight: 500;
}

.category-tag {
  background: #e6f7ff;
  color: #1890ff;
  padding: 2px 8px;
  border-radius: 12px;
  font-size: 12px;
}

.categories-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.category-item {
  display: flex;
  align-items: center;
  gap: 16px;
  padding: 16px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
}

.category-info {
  flex: 1;
}

.category-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.category-desc {
  font-size: 14px;
  color: #666;
}

.category-stats {
  font-size: 14px;
  color: #999;
}

.category-actions {
  display: flex;
  gap: 4px;
}

.security-options {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 20px;
}

.option-card {
  padding: 20px;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
}

.option-card h3 {
  margin: 0 0 8px 0;
  color: #333;
}

.option-card p {
  margin: 0 0 16px 0;
  color: #666;
  font-size: 14px;
}

.profile-form {
  max-width: 400px;
}

.form-group {
  margin-bottom: 16px;
}

.form-group label {
  display: block;
  margin-bottom: 8px;
  color: #333;
  font-weight: 500;
}

.form-input {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
  box-sizing: border-box;
}

.form-input:focus {
  outline: none;
  border-color: #1890ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.2);
}

/* 安全设置样式 */
.security-section {
  margin-bottom: 32px;
}

.security-section h3 {
  font-size: 18px;
  margin-bottom: 16px;
  color: #333;
}

.security-cards {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(300px, 1fr));
  gap: 16px;
}

.security-card {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 20px;
}

.card-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 12px;
}

.card-header h4 {
  margin: 0;
  font-size: 16px;
  color: #333;
}

.status-badge {
  padding: 4px 8px;
  border-radius: 4px;
  font-size: 12px;
  font-weight: 500;
}

.status-badge.good {
  background: #f6ffed;
  color: #52c41a;
  border: 1px solid #b7eb8f;
}

.status-badge.warning {
  background: #fff7e6;
  color: #fa8c16;
  border: 1px solid #ffd591;
}

.card-info {
  margin: 12px 0;
  font-size: 14px;
  color: #666;
}

.encrypt-options {
  margin-top: 16px;
}

.form-select {
  width: 100%;
  padding: 8px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
  background: white;
}

.devices-list {
  margin: 16px 0;
}

.device-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 12px;
  border: 1px solid #e9ecef;
  border-radius: 6px;
  margin-bottom: 8px;
}

.device-info {
  flex: 1;
}

.device-name {
  display: flex;
  align-items: center;
  gap: 8px;
  font-weight: 500;
  margin-bottom: 4px;
}

.device-details {
  font-size: 12px;
  color: #666;
  display: flex;
  gap: 16px;
}

.current-device {
  color: #52c41a;
  font-size: 12px;
  font-weight: 500;
}

.biometric-controls {
  margin-top: 16px;
}

.security-logs {
  margin-top: 16px;
}

.log-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 8px 0;
  border-bottom: 1px solid #f0f0f0;
}

.log-item:last-child {
  border-bottom: none;
}

.log-icon {
  font-size: 16px;
  margin-top: 2px;
}

.log-content {
  flex: 1;
}

.log-action {
  font-size: 14px;
  color: #333;
  margin-bottom: 2px;
}

.log-time {
  font-size: 12px;
  color: #666;
}

/* 个人资料样式 */
.profile-section {
  margin-bottom: 32px;
}

.profile-section h3 {
  font-size: 18px;
  margin-bottom: 16px;
  color: #333;
}

.profile-card {
  background: #f8f9fa;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  padding: 20px;
}

.avatar-section {
  text-align: center;
  margin-bottom: 24px;
}

.avatar-container {
  display: inline-block;
  position: relative;
}

.avatar {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  object-fit: cover;
  border: 3px solid #e9ecef;
}

.avatar-placeholder {
  width: 80px;
  height: 80px;
  border-radius: 50%;
  background: #1890ff;
  color: white;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 32px;
  font-weight: bold;
  border: 3px solid #e9ecef;
}

.avatar-change-btn {
  display: block;
  margin: 8px auto 0;
  padding: 4px 12px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 12px;
}

.form-help {
  font-size: 12px;
  color: #666;
  margin-top: 4px;
}

.form-warning {
  font-size: 12px;
  color: #fa8c16;
  margin-top: 4px;
  display: flex;
  align-items: center;
  gap: 8px;
}

.form-actions {
  display: flex;
  gap: 12px;
  margin-top: 20px;
}

.binding-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.binding-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #e9ecef;
  border-radius: 6px;
}

.binding-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.binding-icon {
  font-size: 20px;
}

.binding-name {
  font-weight: 500;
  margin-bottom: 4px;
}

.bound-status {
  color: #52c41a;
  font-size: 12px;
}

.unbound-status {
  color: #999;
  font-size: 12px;
}

.stats-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 16px;
}

.stat-item {
  text-align: center;
  padding: 16px;
  border: 1px solid #e9ecef;
  border-radius: 6px;
}

.stat-label {
  font-size: 12px;
  color: #666;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 20px;
  font-weight: bold;
  color: #333;
}

.data-actions {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.action-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #e9ecef;
  border-radius: 6px;
}

.action-info h4 {
  margin: 0 0 4px 0;
  font-size: 14px;
  color: #333;
}

.action-info p {
  margin: 0;
  font-size: 12px;
  color: #666;
}

/* 弹窗样式 */
.modal-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.5);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 1000;
}

.modal-content {
  background: white;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  max-height: 90vh;
  overflow-y: auto;
}

.modal-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 20px 0;
  border-bottom: 1px solid #e9ecef;
}

.modal-header h3 {
  margin: 0;
  font-size: 18px;
  color: #333;
}

.modal-close {
  background: none;
  border: none;
  font-size: 24px;
  cursor: pointer;
  color: #999;
  padding: 0;
  width: 24px;
  height: 24px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.modal-body {
  padding: 20px;
}

.modal-footer {
  display: flex;
  justify-content: flex-end;
  gap: 12px;
  padding: 0 20px 20px;
  border-top: 1px solid #e9ecef;
}

/* 按钮样式补充 */
.btn-warning {
  padding: 8px 16px;
  background: #fa8c16;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-warning:hover {
  background: #ffa940;
}

/* 加密字段样式 */
.encrypted-field {
  color: #999 !important;
  font-style: italic;
  cursor: help;
}

/* 大型模态框 */
.large-modal {
  max-width: 600px !important;
}

/* 账号详情样式 */
.account-details {
  space-y: 16px;
}

.detail-row {
  display: flex;
  align-items: center;
  margin-bottom: 16px;
  padding: 12px;
  background: #f8f9fa;
  border-radius: 6px;
}

.detail-row label {
  min-width: 100px;
  font-weight: 600;
  color: #495057;
  margin-right: 12px;
}

.detail-value {
  flex: 1;
  color: #212529;
  word-break: break-all;
}

.detail-value-with-copy {
  display: flex;
  align-items: center;
  flex: 1;
  gap: 8px;
}

.password-field {
  font-family: monospace;
  font-size: 14px;
}

.copy-btn {
  background: #e9ecef;
  border: none;
  border-radius: 4px;
  padding: 4px 8px;
  cursor: pointer;
  font-size: 12px;
  color: #6c757d;
  transition: all 0.2s;
}

.copy-btn:hover {
  background: #dee2e6;
  color: #495057;
}

/* 错误消息样式 */
.error-message {
  color: #dc3545;
  font-size: 14px;
  margin-top: 8px;
  padding: 8px 12px;
  background: #f8d7da;
  border: 1px solid #f5c6cb;
  border-radius: 4px;
}

.btn-warning:disabled {
  background: #ccc;
  cursor: not-allowed;
}

.btn-danger {
  padding: 8px 16px;
  background: #ff4d4f;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 14px;
}

.btn-danger:hover {
  background: #ff7875;
}

.btn-danger-text {
  background: none;
  border: none;
  color: #ff4d4f;
  cursor: pointer;
  font-size: 14px;
  text-decoration: underline;
}

.btn-text {
  background: none;
  border: none;
  color: #1890ff;
  cursor: pointer;
  font-size: 12px;
  text-decoration: underline;
}

/* 导出格式选择 */
.export-format-options {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 12px;
  margin-top: 12px;
}

.format-option {
  cursor: pointer;
}

.format-option input[type="radio"] {
  display: none;
}

.format-card {
  border: 2px solid #e9ecef;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
  transition: all 0.2s;
}

.format-option input[type="radio"]:checked + .format-card {
  border-color: #1890ff;
  background: #e6f7ff;
}

.format-card:hover {
  border-color: #1890ff;
  box-shadow: 0 2px 8px rgba(24, 144, 255, 0.2);
}

.format-icon {
  font-size: 32px;
  margin-bottom: 8px;
}

.format-name {
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.format-desc {
  font-size: 12px;
  color: #666;
}

.export-tips {
  margin-top: 20px;
  padding: 12px;
  background: #fffbe6;
  border: 1px solid #ffe58f;
  border-radius: 6px;
  font-size: 13px;
}

.export-tips p {
  margin: 0 0 8px 0;
  color: #d48806;
}

.export-tips ul {
  margin: 0;
  padding-left: 20px;
}

.export-tips li {
  margin-bottom: 4px;
  color: #8c6e1f;
}

/* 备份列表 */
.backup-list {
  max-height: 400px;
  overflow-y: auto;
}

.backup-item {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 16px;
  border: 1px solid #e9ecef;
  border-radius: 8px;
  margin-bottom: 12px;
}

.backup-info {
  display: flex;
  align-items: center;
  gap: 12px;
  flex: 1;
}

.backup-icon {
  font-size: 24px;
}

.backup-details {
  flex: 1;
}

.backup-name {
  font-weight: 500;
  color: #333;
  margin-bottom: 4px;
}

.backup-meta {
  font-size: 12px;
  color: #666;
  display: flex;
  gap: 8px;
}

.backup-actions {
  display: flex;
  gap: 8px;
  align-items: center;
}

/* 空状态 */
.empty-state {
  text-align: center;
  padding: 40px 20px;
}

.empty-icon {
  font-size: 64px;
  margin-bottom: 16px;
  opacity: 0.5;
}

.empty-text {
  font-size: 16px;
  color: #999;
}

/* 导入进度覆盖层 */
.import-progress-overlay {
  position: fixed;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  background: rgba(0, 0, 0, 0.7);
  display: flex;
  align-items: center;
  justify-content: center;
  z-index: 2000;
}

.import-progress-card {
  background: white;
  border-radius: 12px;
  padding: 32px;
  min-width: 300px;
  text-align: center;
}

.progress-icon {
  font-size: 48px;
  margin-bottom: 16px;
}

.progress-text {
  font-size: 16px;
  font-weight: 500;
  color: #333;
  margin-bottom: 20px;
}

.progress-bar {
  height: 8px;
  background: #f0f0f0;
  border-radius: 4px;
  overflow: hidden;
  margin-bottom: 12px;
}

.progress-fill {
  height: 100%;
  background: linear-gradient(90deg, #1890ff, #40a9ff);
  transition: width 0.3s ease;
  border-radius: 4px;
}

.progress-percent {
  font-size: 14px;
  color: #666;
  font-weight: 500;
}

/* 通知样式 */
.notifications-section {
  margin-bottom: 32px;
}

.section-header {
  display: flex;
  align-items: center;
  gap: 12px;
  margin-bottom: 16px;
}

.section-header h3 {
  margin: 0;
  color: #333;
}

.section-header .badge {
  background: #ff4d4f;
  color: white;
  font-size: 12px;
  padding: 2px 8px;
  border-radius: 12px;
  font-weight: 600;
}

.notifications-list {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.notification-item {
  display: flex;
  align-items: flex-start;
  gap: 12px;
  padding: 16px;
  background: #f8f9fa;
  border-left: 3px solid #dee2e6;
  border-radius: 6px;
  transition: all 0.2s;
}

.notification-item:hover {
  background: #e9ecef;
  transform: translateX(2px);
}

.notification-item.priority-5 {
  border-left-color: #f5222d;
  background: #fff1f0;
}

.notification-item.priority-4 {
  border-left-color: #fa8c16;
  background: #fff7e6;
}

.notification-item.priority-3 {
  border-left-color: #fadb14;
  background: #fffbe6;
}

.notification-icon {
  font-size: 20px;
  margin-top: 2px;
}

.notification-content {
  flex: 1;
}

.notification-title {
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.notification-message {
  font-size: 13px;
  color: #666;
  margin-bottom: 4px;
}

.notification-time {
  font-size: 12px;
  color: #999;
}

.notification-priority {
  margin-left: auto;
}

.priority-badge {
  padding: 2px 8px;
  border-radius: 4px;
  font-size: 11px;
  font-weight: 600;
}

.priority-badge.priority-5 {
  background: #fff1f0;
  color: #f5222d;
  border: 1px solid #ffa39e;
}

.priority-badge.priority-4 {
  background: #fff7e6;
  color: #fa8c16;
  border: 1px solid #ffd591;
}

.priority-badge.priority-3 {
  background: #fffbe6;
  color: #d48806;
  border: 1px solid #ffe58f;
}

.view-all-btn {
  margin-top: 12px;
  padding: 10px;
  background: #f0f0f0;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  cursor: pointer;
  width: 100%;
  color: #1890ff;
  font-weight: 500;
  transition: all 0.2s;
}

.view-all-btn:hover {
  background: #e6f7ff;
  border-color: #1890ff;
}

/* 通知统计 */
.notification-stats {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(150px, 1fr));
  gap: 16px;
  margin-bottom: 24px;
}

.notification-stats .stat-item {
  padding: 20px;
  background: #f8f9fa;
  border: 2px solid #e9ecef;
  border-radius: 8px;
  text-align: center;
  cursor: pointer;
  transition: all 0.2s;
}

.notification-stats .stat-item:hover {
  background: #e9ecef;
  border-color: #1890ff;
}

.notification-stats .stat-item.active {
  background: #e6f7ff;
  border-color: #1890ff;
}

.notification-stats .stat-number {
  font-size: 28px;
  font-weight: bold;
  color: #1890ff;
  margin-bottom: 8px;
}

.notification-stats .stat-label {
  font-size: 13px;
  color: #666;
}

/* 通知卡片 */
.notifications-container {
  margin-top: 20px;
}

.notifications-full-list {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.notification-card {
  background: white;
  border: 1px solid #e9ecef;
  border-left: 4px solid #dee2e6;
  border-radius: 8px;
  padding: 20px;
  transition: all 0.2s;
}

.notification-card:hover {
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
  transform: translateY(-2px);
}

.notification-card.priority-5 {
  border-left-color: #f5222d;
}

.notification-card.priority-4 {
  border-left-color: #fa8c16;
}

.notification-card.priority-3 {
  border-left-color: #fadb14;
}

.notification-header {
  display: flex;
  align-items: center;
  gap: 16px;
  margin-bottom: 12px;
}

.notification-icon-large {
  font-size: 28px;
}

.notification-info {
  flex: 1;
}

.notification-title-large {
  font-size: 16px;
  font-weight: 600;
  color: #333;
  margin-bottom: 4px;
}

.notification-time-large {
  font-size: 13px;
  color: #999;
}

.priority-badge-large {
  padding: 4px 12px;
  border-radius: 12px;
  font-size: 12px;
  font-weight: 600;
}

.priority-badge-large.priority-5 {
  background: #fff1f0;
  color: #f5222d;
}

.priority-badge-large.priority-4 {
  background: #fff7e6;
  color: #fa8c16;
}

.priority-badge-large.priority-3 {
  background: #fffbe6;
  color: #d48806;
}

.notification-body {
  font-size: 14px;
  color: #666;
  line-height: 1.6;
}

.notification-body p {
  margin: 0 0 8px 0;
}

.notification-account {
  margin-top: 8px;
  padding: 8px 12px;
  background: #f8f9fa;
  border-radius: 4px;
  font-size: 13px;
}

.notification-account strong {
  color: #1890ff;
}

.notification-actions {
  margin-top: 12px;
  padding-top: 12px;
  border-top: 1px solid #f0f0f0;
}

.action-link {
  padding: 6px 16px;
  background: #1890ff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
  font-size: 13px;
  transition: all 0.2s;
}

.action-link:hover {
  background: #40a9ff;
}

/* 统计图表样式 */
.charts-section {
  margin-top: 32px;
  margin-bottom: 32px;
}

.charts-section > h3 {
  margin-bottom: 24px;
  color: #333;
}

.chart-container {
  background: white;
  border: 1px solid #e9ecef;
  border-radius: 12px;
  padding: 24px;
  margin-bottom: 24px;
}

.chart-header {
  margin-bottom: 20px;
}

.chart-header h4 {
  margin: 0 0 4px 0;
  color: #333;
  font-size: 16px;
}

.chart-subtitle {
  font-size: 13px;
  color: #999;
}

/* 饼图 */
.pie-chart {
  display: grid;
  grid-template-columns: 1fr 200px;
  gap: 32px;
  align-items: center;
}

.pie-chart-legend {
  display: flex;
  flex-direction: column;
  gap: 12px;
}

.legend-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 8px;
  border-radius: 6px;
  transition: all 0.2s;
}

.legend-item:hover {
  background: #f8f9fa;
}

.legend-color {
  width: 16px;
  height: 16px;
  border-radius: 4px;
  flex-shrink: 0;
}

.legend-info {
  display: flex;
  justify-content: space-between;
  align-items: center;
  flex: 1;
}

.legend-name {
  font-size: 14px;
  color: #333;
  font-weight: 500;
}

.legend-value {
  font-size: 13px;
  color: #666;
}

.pie-chart-visual {
  position: relative;
  width: 200px;
  height: 200px;
}

.pie-svg {
  width: 100%;
  height: 100%;
}

.pie-center {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  text-align: center;
}

.pie-total {
  font-size: 32px;
  font-weight: bold;
  color: #1890ff;
  line-height: 1;
  margin-bottom: 4px;
}

.pie-label {
  font-size: 13px;
  color: #666;
}

/* 柱状图 */
.line-chart {
  position: relative;
  height: 250px;
  padding: 20px 0;
}

.chart-grid {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 40px;
  display: flex;
  flex-direction: column;
  justify-content: space-between;
}

.grid-line {
  height: 1px;
  background: #f0f0f0;
}

.chart-bars {
  position: relative;
  display: flex;
  justify-content: space-around;
  align-items: flex-end;
  height: 100%;
  padding-bottom: 40px;
  gap: 8px;
}

.bar-item {
  flex: 1;
  display: flex;
  flex-direction: column;
  align-items: center;
  height: 100%;
}

.bar-wrapper {
  flex: 1;
  width: 100%;
  display: flex;
  align-items: flex-end;
  justify-content: center;
}

.bar {
  width: 100%;
  max-width: 50px;
  border-radius: 6px 6px 0 0;
  position: relative;
  transition: all 0.3s ease;
  cursor: pointer;
  display: flex;
  align-items: flex-start;
  justify-content: center;
  padding-top: 8px;
}

.bar:hover {
  opacity: 0.8;
  transform: translateY(-4px);
}

.bar-value {
  font-size: 12px;
  font-weight: 600;
  color: white;
}

.bar-label {
  margin-top: 8px;
  font-size: 12px;
  color: #666;
  white-space: nowrap;
}

/* 健康度仪表盘 */
.health-score-chart {
  display: grid;
  grid-template-columns: 280px 1fr;
  gap: 32px;
  align-items: center;
}

.score-gauge {
  position: relative;
  width: 280px;
  height: 160px;
}

.gauge-svg {
  width: 100%;
  height: 100%;
}

.gauge-center {
  position: absolute;
  bottom: 20px;
  left: 50%;
  transform: translateX(-50%);
  text-align: center;
}

.gauge-score {
  font-size: 48px;
  font-weight: bold;
  color: #1890ff;
  line-height: 1;
  margin-bottom: 8px;
}

.gauge-label {
  font-size: 16px;
  color: #666;
  font-weight: 500;
}

.health-details {
  display: grid;
  grid-template-columns: repeat(2, 1fr);
  gap: 16px;
}

.health-item {
  display: flex;
  align-items: center;
  gap: 12px;
  padding: 16px;
  background: #f8f9fa;
  border-radius: 8px;
  transition: all 0.2s;
}

.health-item:hover {
  background: #e9ecef;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

.health-icon {
  font-size: 24px;
}

.health-text {
  flex: 1;
  font-size: 14px;
  color: #666;
}

.health-count {
  font-size: 20px;
  font-weight: bold;
  color: #52c41a;
}

.health-count.warning {
  color: #fa8c16;
}

@media (max-width: 768px) {
  .dashboard-main {
    flex-direction: column;
    padding: 10px;
  }

  .sidebar {
    width: 100%;
    position: static;
  }

  .nav-menu {
    flex-direction: row;
    overflow-x: auto;
  }

  .menu-item {
    white-space: nowrap;
    border-left: none;
    border-bottom: 3px solid transparent;
  }

  .menu-item.active {
    border-left: none;
    border-bottom-color: #1890ff;
  }

  .stats-grid {
    grid-template-columns: repeat(2, 1fr);
  }

  .accounts-grid {
    grid-template-columns: 1fr;
  }

  .search-bar {
    flex-direction: column;
  }

  .category-filter {
    width: 100%;
  }

  .pie-chart {
    grid-template-columns: 1fr;
  }

  .pie-chart-visual {
    margin: 0 auto;
  }

  .health-score-chart {
    grid-template-columns: 1fr;
  }

  .score-gauge {
    margin: 0 auto;
  }

  .health-details {
    grid-template-columns: 1fr;
  }
}

/* 主密码修改向导样式 */
.password-change-wizard {
  max-width: 600px;
}

.wizard-steps {
  display: flex;
  align-items: center;
  justify-content: center;
  padding: 24px 20px;
  background: #fafafa;
}

.wizard-step {
  display: flex;
  flex-direction: column;
  align-items: center;
  gap: 8px;
}

.step-number {
  width: 36px;
  height: 36px;
  border-radius: 50%;
  background: #e8e8e8;
  color: #999;
  display: flex;
  align-items: center;
  justify-content: center;
  font-weight: 600;
  font-size: 16px;
  transition: all 0.3s;
}

.wizard-step.active .step-number {
  background: #1890ff;
  color: white;
  box-shadow: 0 0 0 4px rgba(24, 144, 255, 0.2);
}

.wizard-step.completed .step-number {
  background: #52c41a;
  color: white;
}

.step-label {
  font-size: 12px;
  color: #999;
  transition: all 0.3s;
}

.wizard-step.active .step-label {
  color: #1890ff;
  font-weight: 600;
}

.wizard-step.completed .step-label {
  color: #52c41a;
}

.wizard-line {
  width: 80px;
  height: 2px;
  background: #e8e8e8;
  margin: 0 16px;
  margin-bottom: 24px;
  transition: all 0.3s;
}

.wizard-line.active {
  background: #52c41a;
}

.wizard-content {
  min-height: 280px;
  animation: fadeIn 0.3s;
}

@keyframes fadeIn {
  from {
    opacity: 0;
    transform: translateY(10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.info-box {
  padding: 16px;
  border-radius: 8px;
  margin-bottom: 20px;
}

.info-box.warning {
  background: #fff7e6;
  border: 1px solid #ffd591;
}

.info-box.warning h4 {
  margin: 0 0 8px 0;
  color: #fa8c16;
  font-size: 14px;
}

.info-box.warning p {
  margin: 0;
  color: #d46b08;
  font-size: 13px;
}

.info-box.info {
  background: #e6f7ff;
  border: 1px solid #91d5ff;
}

.info-box.info p {
  margin: 0;
  color: #0050b3;
  font-size: 13px;
}

.info-stats {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
  margin-bottom: 20px;
}

.stat-item {
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 16px;
  text-align: center;
}

.stat-label {
  font-size: 13px;
  color: #666;
  margin-bottom: 8px;
}

.stat-value {
  font-size: 24px;
  font-weight: 600;
  color: #1890ff;
}

.processing-container {
  display: flex;
  flex-direction: column;
  align-items: center;
  padding: 20px 0;
}

.progress-circle {
  position: relative;
  margin-bottom: 24px;
}

.progress-text {
  position: absolute;
  top: 50%;
  left: 50%;
  transform: translate(-50%, -50%);
  font-size: 24px;
  font-weight: 600;
  color: #1890ff;
}

.processing-title {
  margin: 0 0 8px 0;
  color: #333;
  font-size: 16px;
}

.processing-info {
  margin: 0 0 20px 0;
  color: #666;
  font-size: 14px;
}

.progress-bar-container {
  width: 100%;
  height: 8px;
  background: #e8e8e8;
  border-radius: 4px;
  overflow: hidden;
}

.progress-bar-fill {
  height: 100%;
  background: linear-gradient(90deg, #1890ff, #40a9ff);
  border-radius: 4px;
  transition: width 0.3s ease;
}

.success-message {
  color: #52c41a;
  font-size: 13px;
  margin-top: 4px;
}

.error-message {
  color: #ff4d4f;
  font-size: 13px;
  margin-top: 4px;
}

.btn-primary:disabled {
  background: #d9d9d9;
  cursor: not-allowed;
  opacity: 0.6;
}

/* 骨架屏加载动画样式 */
.skeleton-card {
  pointer-events: none;
}

.skeleton {
  background: linear-gradient(
    90deg,
    #f0f0f0 25%,
    #e8e8e8 50%,
    #f0f0f0 75%
  );
  background-size: 200% 100%;
  animation: skeleton-loading 1.5s ease-in-out infinite;
  border-radius: 4px;
}

@keyframes skeleton-loading {
  0% {
    background-position: 200% 0;
  }
  100% {
    background-position: -200% 0;
  }
}

.skeleton-title {
  height: 20px;
  width: 60%;
}

.skeleton-actions {
  height: 20px;
  width: 120px;
}

.skeleton-line {
  height: 16px;
  width: 100%;
  margin-bottom: 8px;
}

.skeleton-line.short {
  width: 80%;
}

.skeleton-line.shorter {
  width: 60%;
}

/* 骨架屏卡片间距调整 */
.skeleton-card .card-header {
  margin-bottom: 12px;
}

.skeleton-card .card-content {
  padding-top: 8px;
}

/* 快捷键帮助样式 */
.shortcuts-help {
  margin-top: 32px;
  padding: 24px;
  background: white;
  border-radius: 12px;
  border: 1px solid #e8e8e8;
}

.shortcuts-help h3 {
  margin: 0 0 20px 0;
  color: #333;
  font-size: 18px;
}

.shortcuts-grid {
  display: grid;
  grid-template-columns: repeat(auto-fit, minmax(200px, 1fr));
  gap: 16px;
}

.shortcut-item {
  display: flex;
  align-items: center;
  justify-content: space-between;
  padding: 12px 16px;
  background: #f7f7f7;
  border-radius: 8px;
  border: 1px solid #e8e8e8;
  transition: all 0.2s;
}

.shortcut-item:hover {
  background: #e6f7ff;
  border-color: #91d5ff;
  transform: translateY(-2px);
  box-shadow: 0 2px 8px rgba(0,0,0,0.08);
}

.shortcut-key {
  display: inline-block;
  padding: 4px 10px;
  background: white;
  border: 2px solid #d9d9d9;
  border-radius: 6px;
  font-family: 'Courier New', monospace;
  font-size: 13px;
  font-weight: 600;
  color: #1890ff;
  box-shadow: 0 2px 0 rgba(0,0,0,0.1);
}

.shortcut-desc {
  color: #666;
  font-size: 14px;
}

@media (max-width: 768px) {
  .shortcuts-grid {
    grid-template-columns: 1fr;
  }
}

/* 高级搜索样式 */
.advanced-search-panel {
  background: white;
  border: 1px solid #e8e8e8;
  border-radius: 8px;
  padding: 20px;
  margin-bottom: 20px;
  animation: slideDown 0.3s ease-out;
}

@keyframes slideDown {
  from {
    opacity: 0;
    transform: translateY(-10px);
  }
  to {
    opacity: 1;
    transform: translateY(0);
  }
}

.advanced-search-panel h4 {
  margin: 0 0 16px 0;
  color: #333;
  font-size: 16px;
}

.search-filters {
  display: flex;
  flex-direction: column;
  gap: 16px;
}

.filter-row {
  display: grid;
  grid-template-columns: 1fr 1fr;
  gap: 16px;
}

.filter-group {
  display: flex;
  flex-direction: column;
  gap: 6px;
}

.filter-group label {
  font-size: 13px;
  color: #666;
  font-weight: 500;
}

.search-history {
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

.search-history label {
  font-size: 13px;
  color: #666;
  margin-bottom: 8px;
  display: block;
}

.history-tags {
  display: flex;
  flex-wrap: wrap;
  gap: 8px;
}

.history-tag {
  display: inline-block;
  padding: 4px 12px;
  background: #f0f0f0;
  border-radius: 12px;
  font-size: 13px;
  color: #666;
  cursor: pointer;
  transition: all 0.2s;
}

.history-tag:hover {
  background: #1890ff;
  color: white;
}

.search-actions {
  display: flex;
  gap: 12px;
  margin-top: 16px;
  padding-top: 16px;
  border-top: 1px solid #e8e8e8;
}

@media (max-width: 768px) {
  .filter-row {
    grid-template-columns: 1fr;
  }

  .search-actions {
    flex-direction: column;
  }

  .search-actions button {
    width: 100%;
  }
}

/* 批量操作样式 */
.batch-toolbar {
  background: #f0f7ff;
  border: 1px solid #91d5ff;
  border-radius: 8px;
  padding: 12px 16px;
  margin-bottom: 16px;
  display: flex;
  justify-content: space-between;
  align-items: center;
  animation: slideDown 0.3s ease-out;
}

.batch-info {
  display: flex;
  align-items: center;
  gap: 12px;
}

.checkbox-label {
  display: flex;
  align-items: center;
  gap: 8px;
  cursor: pointer;
  font-size: 14px;
  color: #333;
  user-select: none;
}

.batch-checkbox,
.account-checkbox {
  width: 18px;
  height: 18px;
  cursor: pointer;
  accent-color: #1890ff;
}

.batch-actions {
  display: flex;
  gap: 12px;
  align-items: center;
}

.batch-select {
  padding: 6px 12px;
  border: 1px solid #d9d9d9;
  border-radius: 6px;
  font-size: 14px;
  cursor: pointer;
  background: white;
}

.btn-danger {
  padding: 8px 16px;
  background: #ff4d4f;
  color: white;
  border: none;
  border-radius: 6px;
  cursor: pointer;
  font-size: 14px;
  transition: all 0.2s;
}

.btn-danger:hover {
  background: #ff7875;
}

.account-title-wrapper {
  display: flex;
  align-items: center;
  gap: 8px;
}

.account-card.batch-selected {
  border-color: #1890ff;
  background: #f0f7ff;
  box-shadow: 0 0 0 2px rgba(24, 144, 255, 0.1);
}

.account-card.batch-selected .account-title {
  color: #1890ff;
  font-weight: 600;
}

@media (max-width: 768px) {
  .batch-toolbar {
    flex-direction: column;
    gap: 12px;
    align-items: stretch;
  }

  .batch-actions {
    flex-direction: column;
    width: 100%;
  }

  .batch-actions button,
  .batch-select {
    width: 100%;
  }
}
</style>